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

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

问题描述

考虑到这段代码,我可以完全确定 finally 块始终执行,无论是什么( )是?

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 将在执行try或catch代码块后调用。

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. 如果JVM首先崩溃;

  3. 如果JVM达到无限循环(或其他一些不可中断的,非终止声明)在尝试捕获块;

  4. 如果操作系统强行终止JVM进程;例如UNIX上的kill -9。

  5. 如果主机系统死机;例如电源故障,硬件错误,操作系统恐慌等等。

  6. 如果最后一个块将由守护程序线程执行,并且所有其他非守护程序线程在最终被调用之前退出。

  1. If you invoke System.exit();
  2. If the JVM crashes first;
  3. If the JVM reaches an infinite loop (or some other non-interruptable, non-terminating statement) in the try or catch block;
  4. If the OS forcibly terminates the JVM process; e.g. "kill -9 " on UNIX.
  5. If the host system dies; e.g. power failure, hardware error, OS panic, etcetera.
  6. If finally block is going to be executed by daemon thread and all other non daemon threads exit before finally is called.

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

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