我試圖理解異常條件從何處派生。我的問題到最後,但我會提出一個可能使其更清晰的例子。例外是基本的,還是可以用條件代替?
以此Java代碼爲例。它具有指向文件的路徑並設置了一個File
對象。如果路徑爲空,則拋出異常。
String path = getPathName();
try {
File file = new File(path);
} catch (NullPointerException e) {
// ...
}
這很難說是一個特殊的情況,不過,如果我們能以這樣的方式,這可能是preferrable修改:
String path = getPathName();
if (path == null) {
path = DEFAULT_PATH;
}
File file = new File(path); # we've removed the need for an exception
但進一步的移動,我們碰上了新的異常時,我們嘗試使File
可讀。
try {
file.setReadable(true);
} catch (SecurityException e) {
// ...
}
我們可以通過檢查兩個條件解決此問題裙子:記住
SecurityManager sm = System.getSecurityManager();
if (sm != null && sm.checkWrite(path)) {
// modify the SecurityManager
} else {
file.setReadable(true);
}
有了這個例子中,我的問題......
如果我們下移堆棧,從Java到OS等等,是否有可能用if-else分支替換所有異常處理代碼?還是有一些例外(硬件?)的根本原因,這意味着它們被「烘烤」到編程中?
爲什麼近距離投票? – sdasdadas
檢查太寬泛的選項。所以,我想有人擔心這會有太多的答案。 – Marcin
啊,我沒有意識到我可以看到推理沒有投票給自己關閉。 – sdasdadas