无论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-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).
}
这种行为使它在各种情况下都非常有用,特别是当您需要执行清理(处置资源)时,尽管在这种情况下使用块通常更好。
任何时候你使用非托管代码请求,如流读取器,db请求等;你想要捕获异常,然后使用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();
}
如果您不想捕获错误,请使用
using (SqlConnection myConn = new SqlConnection("Connectionstring"))
{
myConn.Open();
//make na DB Request
myConn.Close();
}
如果有错误,连接对象将被自动处理,但您没有捕获错误
推荐文章
- 实体框架核心:在上一个操作完成之前,在此上下文中开始的第二个操作
- 如何为构造函数定制Visual Studio的私有字段生成快捷方式?
- 如何使用JSON确保字符串是有效的JSON。网
- AppSettings从.config文件中获取值
- 通过HttpClient向REST API发布一个空体
- 如何检查IEnumerable是否为空或空?
- 自动化invokerrequired代码模式
- 在c#代码中设置WPF文本框的背景颜色
- 在c#中,什么是单子?
- c#和Java中的泛型有什么不同?和模板在c++ ?
- Java 8: Lambda-Streams,过滤方法与异常
- c#线程安全快速(est)计数器
- 如何将此foreach代码转换为Parallel.ForEach?
- 如何分裂()一个分隔字符串到一个列表<字符串>
- 如何转换列表<字符串>列表<int>?