在Java中,可以使用try-catch
语句来捕获异常。当有多层异常的情况下,可以使用多个try-catch
语句来逐层捕获异常。
public class ExceptionHandlingDemo {
public static void main(String[] args) {
try {
// 第一层异常捕获
try {
// 第二层异常捕获
try {
// 执行可能会抛出异常的代码
int result = divide(10, 0);
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
// 捕获第二层异常
System.out.println("Caught ArithmeticException: " + e.getMessage());
}
} catch (NullPointerException e) {
// 捕获第一层异常
System.out.println("Caught NullPointerException: " + e.getMessage());
}
} catch (Exception e) {
// 捕获其他未知异常
System.out.println("Caught Exception: " + e.getMessage());
}
}
public static int divide(int a, int b) throws ArithmeticException {
return a / b;
}
}
在上述代码中,我们有三个层级的异常处理。第一层捕获了NullPointerException
异常,第二层捕获了ArithmeticException
异常,最外层的catch
语句捕获了其他未知异常。
请注意,如果某个层级的异常被捕获后,后续的层级异常捕获将不会执行。