问题
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