gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 05:08:37 25 4
gpt4 key购买 nike

我想知道为什么例如在以下代码段中:

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 块中抛出 SQLException
  • 控制转移到处理 SQLException 的 Catch 子句
  • 当您抛出 InstantiationException
  • 时,Catch 子句突然完成
  • finally 块是通过打印您的文本来执行的
  • 关于java - 在 Catch 异常之前打印出 finally,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15180308/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com