您的位置:首页 > 编程语言 > Java开发

Java多层的异常捕获

2015-11-14 19:55 537 查看
示例程序一:

public class CatchWho {
public static void main(String[] args) {
try {
try {
throw new ArrayIndexOutOfBoundsException();
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println(  "ArrayIndexOutOfBoundsException" +  "/内层try-catch");
}

throw new ArithmeticException();
}
catch(ArithmeticException e) {
System.out.println("发生ArithmeticException");
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println(  "ArrayIndexOutOfBoundsException" + "/外层try-catch");
}
}
}


结果截图:



原因分析:由于在程序中有两个 throw 抛出了两个不同类型的错误,所以,后面紧跟的catch会捕获相应类型的错误,并执行相应的处理办法。

由于

示例程序2:

public class CatchWho2 {
public static void main(String[] args) {
try {
try {
throw new ArrayIndexOutOfBoundsException();
}
catch(ArithmeticException e) {
System.out.println( "ArrayIndexOutOfBoundsException" + "/内层try-catch");
}
throw new ArithmeticException();
}
catch(ArithmeticException e) {
System.out.println("发生ArithmeticException");
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println( "ArrayIndexOutOfBoundsException" + "/外层try-catch");
}
}
}


结果截图:



结论:

可以有多个catch语句块,每个代码块捕获一种异常。在某个try块后有两个不同的catch 块捕获两个相同类型的异常是语法错误。

使用catch语句,只能捕获Exception类及其子类的对象。因此,一个捕获Exception对象的catch语句块可以捕获所有“可捕获”的异常。

将catch(Exception e)放在别的catch块前面会使这些catch块都不执行,因此Java不会编译这个程序。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: