java - 在Catch异常之前打印出Finally

标签 java try-catch operator-precedence finally clause

我想知道为什么,例如在下面的代码片段中:

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"))

我已将每个执行步骤的文本以粗体显示。

总结:

  1. try block 中抛出 SQLException
  2. 控制权转移到处理 SQLException 的 Catch 子句
  3. 当您抛出 InstantiationException 时,Catch 子句突然完成
  4. finally block 通过打印文本来执行

关于java - 在Catch异常之前打印出Finally,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15180308/

相关文章:

Java Swing计时器启动问题

java - 周围的 try/catch 是否会破坏 for 循环?

sql-server - 从TRY…CATCH block 调用时,SQL Server存储过程的返回码为NULL。

关于操作数求值顺序的矛盾

perl - 在 Perl 中绑定(bind)运算符意味着什么?

c# - C#'s operators' 操作顺序

java - 如何在 Java 中连接大整数?

java - 使用反射从 Jar 文件中获取所有类

java - 使用 Jaxws 在 Soap Response 中添加额外的标签或元素

sql-server - sql Try Block中的恢复错误未被捕获