最后怎么用 [英] how to use finally
问题描述
我从未正确理解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 ajava.lang.Throwable
that is not ajava.lang.Exception
, for instance because it is ajava.lang.Error
such asAssertionError
orOutOfMemoryError
. - the try-block completes abruptly using a control flow statement such a
continue
,break
orreturn
- 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屋!