我想知道为什么,例如在下面的代码片段中:
try{
//here happens a SQLException
}
catch(SQLException e){
throw new InstantiationException();
}
finally{
System.out.println("This is the finally");
}
这段代码的结果将首先打印出“This is the finally”
,并且只有在打印出InstantiationException
之后......
最佳答案
来自Java Language Specification: :
If execution of the try block completes abruptly because of a throw of a value V, then there is a choice: (SQLException throw in try clause)
If the run-time type of V is assignment compatible with a catchable exception class of any catch clause of the try statement, then the first (leftmost) such catch clause is selected. The value V is assigned to the parameter of the selected catch clause, and the Block of that catch clause is executed. Then there is a choice:
If the catch block completes normally, then the finally block is executed. Then there is a choice:
If the finally block completes normally, then the try statement completes normally.
If the finally block completes abruptly for any reason, then the try statement completes abruptly for the same reason.
If the catch block completes abruptly for reason R, then the finally block is executed. Then there is a choice: (InstantiationException throw)
If the finally block completes normally, then the try statement completes abruptly for reason R.(System.out.println("This is the finally"))
我已将每个执行步骤的文本以粗体显示。
总结:
- try block 中抛出 SQLException
- 控制权转移到处理 SQLException 的 Catch 子句
- 当您抛出 InstantiationException 时,Catch 子句突然完成
- finally block 通过打印文本来执行
关于java - 在Catch异常之前打印出Finally,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15180308/