【问题标题】:Printing out Finally before the Catch exception在 Catch 异常之前打印出 finally
【发布时间】:2013-03-02 22:43:35
【问题描述】:

我想知道为什么例如在下面的sn-p中:

try{
   //here happens a SQLException
}
catch(SQLException e){
   throw new InstantiationException();
}
finally{
   System.out.println("This is the finally");
}

这段代码的结果将首先打印出"This is the finally",并且只有在它打印出InstantiationException之后...

【问题讨论】:

  • 请阅读The finally Block
  • throw 应该开始一个新线程。在catch 中这样做有意义吗?

标签: java try-catch operator-precedence finally clause


【解决方案1】:

来自Java Language Specification:

如果 try 块的执行由于抛出 一个值V,那么就有一个选择:(SQLException throw in try clause)

如果 V 的运行时类型与可捕获的赋值兼容 try 语句的任何 catch 子句的异常类,然后 第一个(最左边)这样的 catch 子句被选中。值 V 是 分配给所选 catch 子句的参数,以及 Block 该 catch 子句的执行。然后有一个选择:

如果catch块正常完成,那么finally块是 执行。然后有一个选择:

如果 finally 块正常完成,则 try 语句 正常完成。

如果 finally 块由于任何原因突然完成,那么 try 出于同样的原因,语句突然完成。

如果 catch 块由于原因 R 突然完成,那么 finally 块被执行。然后有一个选择:(InstantiationException throw)

如果 finally 块正常完成,则 try 语句 由于 R.(System.out.println("This is the finally"))

的原因突然完成

我在每个执行步骤都用粗体显示。

总结:

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

【讨论】:

    猜你喜欢
    • 2019-03-31
    • 1970-01-01
    • 2021-09-09
    • 1970-01-01
    • 1970-01-01
    • 2011-03-28
    • 2013-10-02
    • 1970-01-01
    相关资源
    最近更新 更多