finally 块是否总是在 Java 中执行? [英] Does a finally block always get executed in Java?

查看:36
本文介绍了finally 块是否总是在 Java 中执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑到这段代码,我可以绝对确定 finally 块总是执行,无论 something() 是什么?p>

Considering this code, can I be absolutely sure that the finally block always executes, no matter what something() is?

try {  
    something();  
    return success;  
}  
catch (Exception e) {   
    return failure;  
}  
finally {  
    System.out.println("I don't know if this will get printed out");
}

推荐答案

是的,finally 会在 trycatch 代码块.

Yes, finally will be called after the execution of the try or catch code blocks.

finally 唯一不会被调用的时间是:

The only times finally won't be called are:

  1. 如果你调用 System.exit()
  2. 如果你调用 Runtime.getRuntime().halt(exitStatus)
  3. 如果 JVM 先崩溃
  4. 如果 JVM 在 trycatch 块中遇到无限循环(或其他一些不可中断、非终止的语句)
  5. 如果操作系统强行终止JVM进程;例如,kill -9 <pid> 在 UNIX 上
  6. 如果主机系统死机;例如,电源故障、硬件错误、操作系统恐慌等
  7. 如果 finally 块将由守护线程执行并且所有其他非守护线程在调用 finally 之前退出
  1. If you invoke System.exit()
  2. If you invoke Runtime.getRuntime().halt(exitStatus)
  3. If the JVM crashes first
  4. If the JVM reaches an infinite loop (or some other non-interruptable, non-terminating statement) in the try or catch block
  5. If the OS forcibly terminates the JVM process; e.g., kill -9 <pid> on UNIX
  6. If the host system dies; e.g., power failure, hardware error, OS panic, et cetera
  7. If the finally block is going to be executed by a daemon thread and all other non-daemon threads exit before finally is called

这篇关于finally 块是否总是在 Java 中执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆