什麼是在catch塊捕獲異常
try {
...
} catch (Nullpointerexception e) { ... }
} catch (Exception e) { ... }
和
try {
...
} catch (Exception e) { ... }
假設之間的區別我有一個NullPointerException
,哪一個是最好的?爲什麼?
什麼是在catch塊捕獲異常
try {
...
} catch (Nullpointerexception e) { ... }
} catch (Exception e) { ... }
和
try {
...
} catch (Exception e) { ... }
假設之間的區別我有一個NullPointerException
,哪一個是最好的?爲什麼?
問:catch(Nullpointerexception e)
和catch(Exception e)
有什麼區別?
答:前者是特定的,後者是一般的。
有時候您想以某種方式處理特定類別的異常(如「NullPointerException」),但有不同的異常類別(如「IOException」)。
一般來說,您應該選擇儘可能處理「最窄」的異常,而不是「處理所有事情」。
「NullPointerException」(和「ArrayIndexOutOfBound」)與其他許多異常之間的另一個顯着差異是NullPointerException是unchecked異常。
注意,那就是,在Java 7中,你可以如何在同一個catch塊趕上多個不同的異常:
Catching Multiple Exceptions in Java 7
// Pre-Java 7 code:
try {
// execute code that may throw 1 of the 3 exceptions below.
} catch(SQLException e) {
logger.log(e);
} catch(IOException e) {
logger.log(e);
} catch(Exception e) {
logger.severe(e);
}
但是現在......
// Java 7 and higher
try {
// execute code that may throw 1 of the 3 exceptions below.
} catch(SQLException | IOException e) {
logger.log(e);
} catch(Exception e) {
logger.severe(e);
}
你應該使用第二個選項,如果處理異常的代碼總是相同的,並且第一個如果你想爲不同的行爲Exception
s。
在任何情況下,對於NullPointerException
s都需要catch子句是非常罕見的,因爲您可以簡單地通過代碼中的空檢查來避免它們(只有在代碼中生成NullPointerException
時才需要catch子句你不能控制,例如在圖書館的內部)。
從Java 7開始,你甚至可以這樣做:
try {
...
} catch (NullPointerException | AnotherException e) {
...
}
避免複製同一機構不同Exception
類。
在Java 7之前,您必須將Exception
處理代碼包含在方法中,並從多個catch子句中調用if以避免其複製。
'Exception'是非常普遍的,'NullPointerException'是特定於'null'對象的,你試圖獲取屬性或訪問方法。最好'catch'你的特定異常(在'NullPointerException'的情況下),否則你可能會隱藏你的代碼中的一些問題,在捕獲一般異常時應該修復這些問題。 – Tom