无论finally块中的内容是什么,它总是被执行(几乎),那么将代码封闭到它或不封闭它之间有什么区别呢?
当前回答
最后,如:
try {
// do something risky
} catch (Exception ex) {
// handle an exception
} finally {
// do any required cleanup
}
是try. catch块之后执行代码的保证机会,而不管try块是否抛出异常。
这使得它非常适合于释放资源、db连接、文件句柄等。
其他回答
finally块对于清理try块中分配的任何资源以及运行即使出现异常也必须执行的任何代码很有价值。无论try块如何退出,控件总是传递给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
}
最后,如:
try {
// do something risky
} catch (Exception ex) {
// handle an exception
} finally {
// do any required cleanup
}
是try. catch块之后执行代码的保证机会,而不管try块是否抛出异常。
这使得它非常适合于释放资源、db连接、文件句柄等。
啊…我想我明白你的意思了!我花了一点时间……你可能想知道“为什么把它放在finally块中,而不是放在finally块之后,并且完全在try-catch-finally之外”。
例如,这可能是因为抛出错误时您正在停止执行,但您仍然希望清理资源,例如打开的文件、数据库连接等。
使用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).
}
这种行为使它在各种情况下都非常有用,特别是当您需要执行清理(处置资源)时,尽管在这种情况下使用块通常更好。
推荐文章
- 何时使用IList,何时使用List
- ConfigurationManager。AppSettings在.NET Core 2.0中可用?
- 在c#的控制台应用程序中使用'async
- 在单元测试中设置HttpContext.Current.Session
- 如何开始开发Internet Explorer扩展?
- 更新行,如果它存在,否则插入逻辑实体框架
- 在什么情况下SqlConnection会自动被征召到环境事务范围事务中?
- 用c#解析JSON
- Windows窗体中的标签的换行
- 为什么在c#中使用finally ?
- 为什么我不能在c#中有抽象静态方法?
- net HttpClient。如何POST字符串值?
- 我如何使一个方法的返回类型泛型?
- 何时处理CancellationTokenSource?
- 如何获取正在执行的程序集版本?