最后怎么用 [英] how to use finally

查看:125
本文介绍了最后怎么用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从未正确理解finally语句的使用。任何人都可以告诉我之间的区别:

I never properly understood the use of the finally statement. Can anyone tell me what the difference is between:

try {
    a;
    block;
    off;
    statements;
} catch (Exception e) {
    handle;
    exception;
    e;
} finally {
    do;
    some;
    cleanup;
}

一方面:

try {
    a;
    block;
    off;
    statements;
} catch (Exception e) {
    handle;
    exception;
    e;
}
do;
some;
cleanup;

另一个

推荐答案

如果


  • 尝试 -block完成,它们会有所不同抛出 java.lang.Throwable ,这不是 java.lang.Exception ,例如因为它是一个 java.lang.Error ,例如 AssertionError OutOfMemoryError

  • try-block使用控制流语句突然完成,例如 continue break return

  • catch-block突然完成(通过抛出任何throwable或使用控制流语句)

  • the try-block completes by throwing a java.lang.Throwable that is not a java.lang.Exception, for instance because it is a java.lang.Error such as AssertionError or OutOfMemoryError.
  • the try-block completes abruptly using a control flow statement such a continue, break or return
  • the catch-block completes abruptly (by throwing any throwable, or using a control flow statement)

更一般地说,java语言保证在try语句完成之前执行finally块。 (请注意,如果try-statement没有完成,则无法保证finally。语句可能由于各种原因而无法完成,包括硬件关闭,操作系统关闭,VM关闭(例如由于 System.exit ),等待的线程( Thread.suspend() synchronized Object.wait() Thread.sleep())或者正忙着(无限循环,,,, )。

More generally, the java language guarantees that a finally block is executed before the try-statement completes. (Note that if the try-statement does not complete, there is no guarantee about the finally. A statement might not complete for a variety of reasons, including hardware shutdown, OS shutdown, VM shutdown (for instance due to System.exit), the thread waiting (Thread.suspend(), synchronized, Object.wait(), Thread.sleep()) or being otherwise busy (endless loops, ,,,).

所以,一个最后块是一个比方法结束更好的清理行动的地方身体,但本身仍然无法保证清理工作。

So, a finally block is a better place for clean-up actions than the end of the method body, but in itself, still can not guarantee cleanup exeuction.

这篇关于最后怎么用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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