为什么在 C# 中使用 finally?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/547791/
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
Why use finally in C#?
提问by Rodrigo
Whatever is inside finally blocks is executed (almost) always, so what's the difference between enclosing code into it or leaving it unclosed?
finally 块中的任何内容(几乎)总是被执行,那么将代码封闭在其中或不封闭它之间有什么区别?
采纳答案by Kevin Pang
The code inside a finally block will get executed regardless of whether or not there is an exception. This comes in very handy when it comes to certain housekeeping functions you need to always run like closing connections.
无论是否有异常,finally 块中的代码都会被执行。当涉及到某些需要始终像关闭连接一样运行的内务处理功能时,这非常方便。
Now, I'm guessingyour question is why you should do this:
现在,我猜你的问题是为什么你应该这样做:
try
{
doSomething();
}
catch
{
catchSomething();
}
finally
{
alwaysDoThis();
}
When you can do this:
当你可以这样做时:
try
{
doSomething();
}
catch
{
catchSomething();
}
alwaysDoThis();
The answer is that a lot of times the code inside your catch statement will either rethrow an exception or break out of the current function. With the latter code, the "alwaysDoThis();" call won't execute if the code inside the catch statement issues a return or throws a new exception.
答案是很多时候,catch 语句中的代码要么重新抛出异常,要么跳出当前函数。使用后一个代码,“alwaysDoThis();” 如果 catch 语句中的代码发出返回或抛出新异常,则不会执行调用。
回答by Matt Briggs
Because finally will get executed even if you do not handle an exception in a catch block.
因为即使您没有在 catch 块中处理异常, finally 也会被执行。
回答by Chris Doggett
Say you need to set the cursor back to the default pointer instead of a waiting (hourglass) cursor. If an exception is thrown before setting the cursor, and doesn't outright crash the app, you could be left with a confusing cursor.
假设您需要将光标设置回默认指针而不是等待(沙漏)光标。如果在设置光标之前抛出异常,并且没有使应用程序彻底崩溃,则您可能会遇到令人困惑的光标。
回答by David Alpert
finally
, as in:
finally
,如:
try {
// do something risky
} catch (Exception ex) {
// handle an exception
} finally {
// do any required cleanup
}
is a guaranteed opportunity to execute code after your try..catch
block, regardless of whether or not your try block threw an exception.
是在try..catch
块之后执行代码的保证机会,无论您的 try 块是否引发异常。
That makes it perfect for things like releasing resources, db connections, file handles, etc.
这使它非常适合释放资源、数据库连接、文件句柄等。
回答by cgreeno
The finally blockis valuable for cleaning up any resources allocated in the try block as well as running any code that must execute even if there is an exception. Control is always passed to the finally block regardless of how the try block exits.
finally 块对于清理在 try 块中分配的任何资源以及运行任何即使出现异常也必须执行的代码很有价值。不管 try 块如何退出,控制总是传递给 finally 块。
回答by Beska
Ahh...I think I see what you're saying! Took me a sec...you're wondering "why place it in the finally block instead of after the finally block and completely outside the try-catch-finally".
啊……我想我明白你在说什么了!花了我一秒钟......你想知道“为什么把它放在 finally 块中而不是放在 finally 块之后并且完全在 try-catch-finally 之外”。
As an example, it might be because you are halting execution if you throw an error, but you still want to clean up resources, such as open files, database connections, etc.
举个例子,这可能是因为如果你抛出一个错误,你正在暂停执行,但你仍然想清理资源,比如打开的文件、数据库连接等。
回答by markom
Sometimes you don't want to handle an exception (no catch block), but you want some cleanup code to execute.
有时您不想处理异常(没有 catch 块),但您希望执行一些清理代码。
For example:
例如:
try
{
// exception (or not)
}
finally
{
// clean up always
}
回答by Noldorin
Most advantages of using try-finally have already been pointed out, but I thought I'd add this one:
已经指出了使用 try-finally 的大多数优点,但我想我会添加这个:
try
{
// Code here that might throw an exception...
if (arbitraryCondition)
{
return true;
}
// Code here that might throw an exception...
}
finally
{
// Code here gets executed regardless of whether "return true;" was called within the try block (i.e. regardless of the value of arbitraryCondition).
}
This behaviour makes it very useful in various situations, particularly when you need to perform cleanup (dispose resources), though a usingblock is often better in this case.
这种行为使它在各种情况下都非常有用,特别是当您需要执行清理(处置资源)时,尽管在这种情况下using块通常更好。
回答by Bob The Janitor
any time you use unmanaged code requests like stream readers, db requests, etc; and you want to catch the exception then use try catch finally and close the stream, data reader, etc. in the finally, if you don't when it errors the connection doesn't get closed, this is really bad with db requests
任何时候您使用非托管代码请求,如流读取器、数据库请求等;并且您想捕获异常,然后使用 try catch finally 并在 finally 中关闭流、数据读取器等,如果您在出错时不这样做,则连接不会关闭,这对于 db 请求来说真的很糟糕
SqlConnection myConn = new SqlConnection("Connectionstring");
try
{
myConn.Open();
//make na DB Request
}
catch (Exception DBException)
{
//do somehting with exception
}
finally
{
myConn.Close();
myConn.Dispose();
}
if you don't want to catch the error then use
如果您不想捕获错误,请使用
using (SqlConnection myConn = new SqlConnection("Connectionstring"))
{
myConn.Open();
//make na DB Request
myConn.Close();
}
and the connection object will be disposed of automatically if there is an error, but you don't capture the error
如果出现错误,连接对象将被自动处理,但您没有捕获错误
回答by Prateek Gupta
Finally statements can execute even after return.
即使在返回之后,finally 语句也可以执行。
private int myfun()
{
int a = 100; //any number
int b = 0;
try
{
a = (5 / b);
return a;
}
catch (Exception ex)
{
Response.Write(ex.Message);
return a;
}
// Response.Write("Statement after return before finally"); -->this will give error "Syntax error, 'try' expected"
finally
{
Response.Write("Statement after return in finally"); // --> This will execute , even after having return code above
}
Response.Write("Statement after return after finally"); // -->Unreachable code
}