Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
372 views
in Technique[技术] by (71.8m points)

java - 是否finally块总是用Java执行?(Does a finally block always get executed in Java?)

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

(考虑到这段代码,我能绝对确定无论something()finally块始终执行吗?)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

(是的,在trycatch代码块执行之后, finally将被调用。)

The only times finally won't be called are:

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

  1. If you invoke System.exit()

    (如果您调用System.exit())

  2. If you invoke Runtime.getRuntime().halt(exitStatus)

    (如果调用Runtime.getRuntime().halt(exitStatus))

  3. If the JVM crashes first

    (如果JVM首先崩溃)

  4. If the JVM reaches an infinite loop (or some other non-interruptable, non-terminating statement) in the try or catch block

    (如果JVM在trycatch块中达到了无限循环(或其他不间断,不终止的语句))

  5. If the OS forcibly terminates the JVM process;

    (操作系统是否强行终止了JVM进程;)

    eg, kill -9 <pid> on UNIX

    (例如,在UNIX上kill -9 <pid>)

  6. If the host system dies;

    (如果主机系统死机;)

    eg, 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块将由守护程序线程执行,并且所有其他非守护程序线程退出,则在调用finally之前)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...