[英]Trying to print multiple catch statements
在下面的代碼中,我試圖打印多個 catch 語句,但我只得到一個。 據我了解,順序是優先的,即第一個 catch 語句匹配將被打印。 但我想打印兩個相關聲明。 有什么辦法嗎?
class Example2{
public static void main(String args[]){
try{
int a[]=new int[7];
a[10]=30/0;
System.out.println("First print statement in try block");
}
catch(ArithmeticException e){
System.out.println("Warning: ArithmeticException");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Warning: ArrayIndexOutOfBoundsException");
}
catch(Exception e){
System.out.println("Warning: Some Other exception");
}
System.out.println("Out of try-catch block...");
}
}
我想要打印出界外和算術語句。 有什么辦法嗎?
這里的問題不是catch
塊的優先級。 首先,您嘗試除以30/0
並生成ArithmeticException
。 永遠不會生成ArrayIndexOutOfBounds
異常,因為您永遠不會嘗試分配給a[10]
。
異常只匹配一個 catch 塊。
你需要合並那些 catch 語句,因為只有一個被觸發
class Example2{
public void main(String args[]){
try{
int a[]=new int[7];
a[10]=30/0;
System.out.println("First print statement in try block");
} catch(ArithmeticException | ArrayIndexOutOfBoundsException e) {
}
System.out.println("Out of try-catch block...");
}
}
然后在 catck 塊中,您可以處理異常。
有一種方法可以使用嵌套的 try 語句打印這兩個異常,如下所示。 否則,就沒有必要打印所有異常。
class ExceptionHandling{
public static void main(String[] args){
try{
try{
String s=null;
System.out.println(s.length());
}
catch(NullPointerException e){
System.out.println(e);
}
int a=4/0;
}
catch(ArithmeticException e){
System.out.println(e);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.