publicclassMain{publicstaticvoidmain(String args[])throwsException{int n =20, result =0;try{
result = n/0;System.out.println("The result is "+result);}catch(ArithmeticException ex){System.out.println("Arithmetic exception occoured: "+ex);try{thrownewNumberFormatException();}catch(NumberFormatException ex1){System.out.println("Chained exception thrown manually : "+ex1);}}}}
结果
上面的代码示例将产生以下结果。
Arithmetic exception occoured :
java.lang.ArithmeticException:/ by zero
Chained exception thrown manually :
java.lang.NumberFormatException
下面是Java中使用catch处理链式异常的另一个例子
publicclassMain{publicstaticvoidmain(String args[])throwsException{int n =20,result =0;try{
result = n/0;System.out.println("The result is"+result);}catch(ArithmeticException ex){System.out.println("Arithmetic exception occoured: "+ex);try{int data =50/0;}catch(ArithmeticException e){System.out.println(e);}System.out.println("rest of the code...");}}}
上面的代码示例将产生以下结果。
Arithmetic exception occoured: java.lang.ArithmeticException:/ by zero
java.lang.ArithmeticException:/ by zero
rest of the code...