如何使用 catch 处理 Java 中的链式异常
问题描述
如何使用 catch 处理链式异常?
解决方案
此示例显示如何使用多个 catch 块处理链式异常。
public class Main{ public static void main (String args[])throws Exception { 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 { throw new NumberFormatException(); } 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
以下是另一个使用 catch 处理 Java 中的链式异常的示例
public class Main{ public static void main (String args[])throws Exception { 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...
java_exceptions.html