Java 最后怎么用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3354823/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 22:34:06  来源:igfitidea点击:

how to use finally

javatry-catch-finally

提问by Martijn

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

我从来没有正确理解 finally 语句的用法。谁能告诉我有什么区别:

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

on the one hand and:

一方面和:

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

On the other

在另一

采纳答案by meriton

They differ if

它们不同,如​​果

  • the try-block completes by throwing a java.lang.Throwablethat is not a java.lang.Exception, for instance because it is a java.lang.Errorsuch as AssertionErroror OutOfMemoryError.
  • the try-block completes abruptly using a control flow statement such a continue, breakor return
  • the catch-block completes abruptly (by throwing any throwable, or using a control flow statement)
  • try-块完成了由投掷java.lang.Throwable不是一个java.lang.Exception,例如,因为它是一个java.lang.ErrorAssertionErrorOutOfMemoryError
  • 尝试块使用控制流语句突然完成,例如continuebreakreturn
  • catch 块突然完成(通过抛出任何可抛出的,或使用控制流语句)

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, ,,,).

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

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

所以,finally块是一个比方法体末尾更好的清理动作的地方,但它本身仍然不能保证清理执行。

回答by Jonathan Park

In proper coding style you don't want to do a catch all as below.

在正确的编码风格中,您不想像下面那样做所有事情。

try{
  [some task] 
}
catch
{
}

What you would want to do is catch specific known errors.

您想要做的是捕获特定的已知错误。

try{
  [some task] 
}
catch(Exception ex)
{
   if([known execption])
     [ignore]
   else
     throw(ex);
}
[Cleanup]

In this case your cleanup code will not be run in the case of an error being thrown again. So we add in the finally which will get run even if a new error is thrown.

在这种情况下,如果再次抛出错误,您的清理代码将不会运行。所以我们添加了 finally ,即使抛出新的错误,它也会运行。

try{
  [some task] 
}
catch(Exception ex)
{
   if([known execption])
     [ignore]
   else
     throw(ex);
}
finally
{
   [Cleanup]
}

回答by YoK

finallyblock executes always.

finally块总是执行。

finallyblock is used for cleanup, like to free resources used within try/catch, close db connections, close sockets, etc.. even when an unhandled exception occurs within your try/catchblock.

finally块用于清理,例如释放try/ 中使用的资源catch,关闭数据库连接,关闭套接字等。即使在try/catch块中发生未处理的异常时也是如此。

The only time the finallyblock doesn't execute is whensystem.exit()is called in try/catchor some error occurs instead of an exception.

finally块不执行的唯一时间system.exit()是在try/ 中调用catch或发生某些错误而不是异常时。

The error in the description above means when Java application exit with conditions like Out Of Memory error. I see some downvotes :( for this reason it seems.

上面描述中的错误意味着当 Java 应用程序退出时出现内存不足错误等情况。我看到一些反对票 :( 似乎是因为这个原因。

回答by Dan

The main difference is that the catchsection might itself throw an exception, break out of a surrounding block, or return from the current method. In that case do; some; cleanup;is not executed.

主要区别在于该catch部分本身可能会抛出异常、跳出周围的块或从当前方法返回。在这种情况下do; some; cleanup;不执行。

With a finallyblock, it is guaranteedthat that code will be executed.

使用finally块,可以保证该代码将被执行。

回答by Jon Skeet

It's basically a bad idea to catch all exceptions - so you need to consider what will happen if an uncaught exception propagates up out of your try/catch or try/catch/finally block. Finally blocks allow you to clean up on the way out.

捕获所有异常基本上是一个坏主意 - 因此您需要考虑如果未捕获的异常从 try/catch 或 try/catch/finally 块中传播出去会发生什么。最后块允许您在出路时清理。

Also:

还:

  • The catch block might throw an exception
  • You may want to return from the try block
  • catch 块可能会抛出异常
  • 你可能想从 try 块中返回

In short, if you want some code to be executed when you leave the try/catch block howeveryou're leaving it (aside from the process being terminated very hard), finally is your friend.

简而言之,如果您想在离开 try/catch 块时执行一些代码,您要离开它(除了非常艰难地终止进程), finally 是您的朋友。

回答by iandisme

The "finally" block will always execute.

“finally”块将始终执行。

In your second example, the cleanup would not occur if the catch block rethrows the exception, or if an uncaught exception occurred in the try block.

在您的第二个示例中,如果 catch 块重新抛出异常,或者在 try 块中发生未捕获的异常,则不会进行清理。

回答by Kyra

From thisforum on GeekInterview:

来自GeekInterview 上的这个论坛:

The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.

finally 块总是在 try 块退出时执行。这确保即使发生意外异常也能执行 finally 块。但 finally 不仅仅用于异常处理——它允许程序员避免通过 return、continue 或 break 意外绕过清理代码。将清理代码放在 finally 块中始终是一个好习惯,即使没有预料到异常也是如此。

回答by ligerdave

Simply one line of explanation:

简单的一行解释:

regardless whether you caught an exception or not, codes in the finallyblock will get executed.

无论您是否捕获到异常,finally块中的代码都会被执行。

the diff between the two pieces you gave here is: the codes in the piece without using finallywill never get executed.

您在此处提供的两部分之间的差异是:未使用的部分中的代码finally将永远不会被执行。

to properly understand finally, all you need to know is that finally= guarantee!

要正确理解finally,您只需要知道finally= 保证!

you can use it to clean up, to help w/ user friendliness or to retry something

你可以用它来清理、帮助用户友好或重试

回答by Nada Aldahleh

In the first example the finally block always gets executed even if you have a return statement in the try clause. The only time it doesn't get executed is when you have System.exit(0).

在第一个示例中,即使在 try 子句中有 return 语句,finally 块也总是会被执行。它没有被执行的唯一时间是当你有 System.exit(0) 时。