在Java编程中,如何使用catch
来处理链异常?
此示例显示如何使用多个catch
块处理链异常。
package com.yiibai;
public class ChainedExceptions {
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
示例-2
以下是在Java中使用catch
来处理链异常的另一个示例
package com.yiibai;
public class ChainedExceptions2 {
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...