Java教程

Java try块嵌套

为什么使用嵌套try块

有时,可能会出现这样的情况: try块的一部分可能导致一个错误,而整个块本身可能导致另一个错误。在这种情况下,必须嵌套异常处理程序。

语法:

....try{
    statement 1;
    statement 2;
    try {
        statement 1;
        statement 2;
    }
    catch(Exception e) {
    }
}
catch(Exception e){
}
....

Java嵌套的try示例

让我们看一下Java嵌套的try块的简单示例。
class Excep6{
    public static void main(String args[]){
        try{
            try{
                System.out.println("going to divide");
                int b =39/0;
            }
            catch(ArithmeticException e){
                System.out.println(e);
            }
            try{
                int a[]=new int[5];
                a[5]=4;
            }
            catch(ArrayIndexOutOfBoundsException e){
                System.out.println(e);
            }
            System.out.println("other statement);
        }catch(Exception e){
            System.out.println("handeled");}
            System.out.println("normal flow..);
        }
    }
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4