java 为什么我们使用 finally 块?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3421486/
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-10-30 01:45:48  来源:igfitidea点击:

Why do we use finally blocks?

java.netfinally

提问by Mohammad Nadeem

As far as I can tell, both of the following code snippets will serve the same purpose. Why have finallyblocks at all?

据我所知,以下两个代码片段都具有相同的目的。为什么有finally块?

Code A:

代码 A:

try { /* Some code */ }
catch { /* Exception handling code */ }
finally { /* Cleanup code */ }

Code B:

代码 B:

try { /* Some code */ }
catch { /* Exception handling code */ }
// Cleanup code

回答by Jon Skeet

  • What happens if an exception you're not handling gets thrown? (I hope you're not catching Throwable...)
  • What happens if you return from inside the try block?
  • What happens if the catch block throws an exception?
  • 如果抛出您未处理的异常会怎样?(我希望你没有赶上Throwable......)
  • 如果从 try 块内部返回会发生什么?
  • 如果 catch 块抛出异常会发生什么?

A finallyblock makes sure that howeveryou exit that block (modulo a few ways of aborting the whole process explicitly), it will get executed. That's important for deterministic cleanup of resources.

一个finally块确保无论您退出该块(以几种显式中止整个过程的方法为模),它都会被执行。这对于资源的确定性清理很重要。

回答by Jesper

Note that (in Java at least, probably also in C#) it's also possible to have a tryblock without a catch, but with a finally. When an exception happens in the tryblock, the code in the finallyblock is run before the exception is thrown higher up:

请注意(至少在 Java 中,可能也在 C# 中)也可以有一个try没有 a的块catch,但有一个finally. 当try块中发生异常时,块中的代码会在finally异常向上抛出之前运行:

InputStream in = new FileInputStream("somefile.xyz");
try {
    somethingThatMightThrowAnException();
}
finally {
    // cleanup here
    in.close();
}

回答by Balaji Natesan

You may want to put the code that you want to anyway get executed irrespective of what happens in your try or catch block.

无论在 try 或 catch 块中发生什么,您都可能希望无论如何都执行您想要执行的代码。

Also if you are using multiple catch and if you want to put some code which is common for all the catch blocks this would be a place to put- but you cannot be sure that the entire code in try has been executed.

此外,如果您正在使用多个 catch 并且如果您想放置一些对所有 catch 块通用的代码,这将是一个放置的地方 - 但您无法确定 try 中的整个代码是否已执行。

For example:

例如:

conn c1 = new connection();
try {
    c1.dosomething();
} catch (ExceptionA exa) {
    handleexA();
    //c1.close();
} catch (ExceptionB exb) {
    handleexB();
    //c1.close();
} finally {
    c1.close();
}

回答by Sruly

Finally always gets executed, where as your code after the catch may not.

最后总是被执行,因为你在 catch 之后的代码可能不会。

回答by Sandeep P

Even though our application is closed forcefully there will be some tasks, which we must execute (like memory release, closing database, release lock, etc), if you write these lines of code in the finallyblock it will execute whether an exception is thrown or not...

即使我们的应用程序被强制关闭,也会有一些我们必须执行的任务(如内存释放、关闭数据库、释放锁等),如果你在finally块中编写这些代码行,无论抛出异常还是抛出异常,它都会执行不是...

Your application may be a collection of threads, Exceptionterminates the thread but not the whole application, in this case finallyis more useful.

你的应用程序可能是一个线程集合,Exception终止线程而不是整个应用程序,在这种情况下finally更有用。

In some cases finallywon't execute such as JVM Fail, Thread terminate, etc.

在某些情况下finally不会执行,例如 JVM Fail、线程终止等。

回答by Ed S.

Because you need that code to execute regardless of any exceptions that may be thrown. For example, you may need to clean up some unmanaged resource (the 'using' construct compiles to a try/finally block).

因为无论可能抛出任何异常,您都需要执行该代码。例如,您可能需要清理一些非托管资源(“using”构造编译为 try/finally 块)。

回答by Mahmoud Hanafy

finallyALWAYS executes, unless the JVM was shut down, finallyjust provides a method to put the cleanup code in one place.

finally始终执行,除非 JVM 被关闭,finally只是提供了一种将清理代码放在一个地方的方法。

It would be too tedious if you had to put the clean up code in each of the catchblocks.

如果您必须将清理代码放在每个catch块中,那就太乏味了。

回答by Egalitarian

There may be times when you want to execute a piece of code no matter what. Whether an exception is thrown or not. Then one uses finally.

有时您无论如何都想执行一段代码。是否抛出异常。然后一个使用finally.

回答by Reshma Kore

If catch block throws any exception then remaining code will not executed hence we have to write finaly block.

如果 catch 块抛出任何异常,那么剩余的代码将不会执行,因此我们必须编写 finaly 块。

回答by Aakersh Sharma

finally block in java can be used to put "cleanup" code such as closing a file, closing connection etc.

java中的finally块可用于放置“清理”代码,例如关闭文件、关闭连接等。



The finally block will not be executed if program exits(either by calling System.exit() or by causing a fatal error that causes the process to abort).

如果程序退出(通过调用 System.exit() 或导致导致进程中止的致命错误),则 finally 块将不会执行。