2014-12-03 57 views
5

如何確定哪種類型的異常被捕獲,如果操作捕獲多個異常?Java - 如何檢查拋出哪種異常類型?

這個例子應該能理解:

try { 
    int x = doSomething(); 
} catch (NotAnInt | ParseError e) { 
    if (/* thrown error is NotAnInt */) { // line 5 
    // printSomething 
    } else { 
    // print something else 
    } 
} 

在第5行,我怎麼能檢查哪些異常被抓?我試過if (e.equals(NotAnInt.class)) {..}但沒有運氣。

注意:NotAnIntParseError是我項目中延伸Exception的類。

+2

使切斷漁獲: 趕上(NotAnInt){}趕上(ParseError){ } – 2014-12-03 20:24:49

+0

[Java-Throwable to Exception]的可能重複(https://stackoverflow.com/questions/12359175/java-throwable-to-exception) – Molham 2018-02-23 12:12:44

回答

13

如果你不能把兩種情況在單獨catch塊,使用:

if (e instanceof NotAnInt) { 
    ... 
} 

這有時是有道理的,當你需要共享邏輯用於2個或更多不同的異常類等。

否則,使用單獨的catch塊:

} catch (NotAnInt e) { 
    ... 
} catch (ParseError e) { 
    ... 
} 
5

使用多個catch塊,一個爲每個例外:

try { 
    int x = doSomething(); 
} 
catch (NotAnInt e) { 
    // print something 
} 
catch (ParseError e){ 
    // print something else 
}