课后作业(异常捕获)

java中的异常捕获语句
Try{
//可能发生运行错误的代码;
}
catch(异常类型 异常对象引用){
//用于处理异常的代码
}
finally{
//用于“善后” 的代码
}
将可能发生异常的代码放进try语句中,程序检测到发生异常时,会抛出一个异常对象,程序会由try语句跳转到catch语句,由catch语句捕捉异常并处理错误,无论是否有异常,finally中的语句都会被执行。
例1
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");
    }
}

}
这是一个嵌套的异常处理,在内层当中,先抛出了一个数组越界异常,然后被内层的catch捕捉,输出ArrayIndexOutOfBoundsException" + "/内层try-catch
然后程序继续抛出一个算术异常,此时进入外层,内层抛出的算数异常被外层第一个catch捕捉,输出发生ArithmeticException,而外层第二个catch不会捕捉任何异常
例2
public class CatchWho {
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捕捉的是算术异常,二者不匹配,所以内层抛出的异常会传递到外层,此时内层剩余代码不会被执行,所以不会再抛出一个算术异常,传递到外层的数组越界异常被外层第二个catch捕捉,输出ArrayIndexOutOfBoundsException" + "/外层try-catch
例3

public class SystemExitAndFinally {

public static void main(String[] args)
{

    try{


        System.out.println("in main");

        throw new Exception("Exception is thrown in main");

        //System.exit(0);


    }

    catch(Exception e)

    {

        System.out.println(e.getMessage());

       // System.exit(0);

    }

    finally

    {

        System.out.println("in finally");

    }

}

}
这段代码说明了finally一定会执行是有例外的,如果去掉第二处注释,程序捕捉异常之后执行System.exit(0);,程序会直接结束,不执行finally语句,但如果去掉第一处注释,由于抛出了异常,程序直接跳转到catch语句,所以不会执行try后面的System.exit(0);,因此仍然会执行finally语句

posted @ 2025-11-05 19:20  lagranSun  阅读(7)  评论(0)    收藏  举报