Exception Handling with Multiple catch block [duplicate]

二次信任 提交于 2019-12-20 04:09:56

问题


Here is my program.

try {
    int a = 1/0;
}
catch(Exception e) {
    system.out.println("Exception block"+e);
}
catch(ArithmeticException e) {
    system.out.println("Inside ArithmeticException block");
}
finally {
    system.out.println("Inside Finally block");
}

In the above program i have two catch blocks and one finally block.

Which catch block will execute? Because I define the parent catch block first. So it leads to an error? Can any one help me?

I assumed that "ArithmeticException and Finally block will be executed"


回答1:


Catching Exception class will not give any error. However, it is not recommended.

In this case, Exception catch block will execute first and then finally block will execute.

If you want that your ArithmeticException block should execute, put this block before Exception catch block.

Update code -

    try{
        int a = 1/0;
    }        
    catch(ArithmeticException e){
        System.out.println("Inside ArithmeticException block");
    }
    catch(Exception e) {
        System.out.println("Exception block"+e);
    }
    finally{
        System.out.println("Inside Finally block");
    }



回答2:


Catching Exception class will not give any error.

In this case, Exception catch block will execute first and then finally block will execute.

If you want that your ArithmeticException block should execute, put this block before Exception catch block.

Here is Updated code

 try {
    int a = 1/0;
}
catch(Exception e) {
    System.out.println("Exception block"+e);
}
finally {
    System.out.println("Inside Finally block");
}
} 


来源:https://stackoverflow.com/questions/40694357/exception-handling-with-multiple-catch-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!