简体   繁体   English

与仅在 try 语句之后编写代码相比,finally 块是什么?

[英]What is the finally block for compared to just writing code after the try statement?

In other words, how are these two different?换句话说,这两者有何不同?

try
{
    // Something that can throw an error
}
catch
{
    // Handle the error
}
finally
{
    // Something that runs after the try statement
}

vs.对比

try
{
    // Something that can throw an error
}
catch
{
    // Handle the error
}
// Something that runs after the try statement

finally block always executes. finally块总是执行。

You can be sure, that this block will be executed no matter what.您可以确定,无论如何都会执行此块。

Literally it is something like:从字面上看,它类似于:

Try something, catch some exceptions(if told to and if they are there) and execute the finally block finally.尝试一些东西,捕捉一些异常(如果被告知并且它们在那里)并最终执行 finally 块。

If there is a break in the try block or an exception, it may cause the program to halt.如果 try 块中出现中断或异常,可能会导致程序停止。 In cases like these code that is mandarory to be executed, like closing open connections and returning items to the connection pools are writen in the finally block.在像这些必须执行的代码的情况下,例如关闭打开的连接和将项目返回到连接池都写在 finally 块中。 The finally block ensures that the code written inside it will be executed. finally 块确保写入其中的代码将被执行。

If you only ever use general catches (ie catch without args or catch(Exception ex) ), whether to put code in finally or after try/catch is basically a stylistic choice, as both a finally block and code after a try/catch will execute in any situation (barring deliberate escape mechanisms such as return ).如果你永远只能用一般渔获量(即catch不ARGS或catch(Exception ex) ),是否将代码放在finally或之后try/catch基本上是一个风格上的选择,同时作为finally块和后代码try/catch会在任何情况下执行(除非故意逃避机制,例如return )。

However, if you use a narrow catch , and the exception isn't caught, what will happen is the finally block will still execute, however the code after the try/catch won't.但是,如果您使用窄catch并且没有捕获异常,将会发生的是finally块仍然会执行,但是try/catch之后的代码不会。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM