最终块中的任何内容都(几乎)总是被执行,那么将代码封装在其中和不关闭它之间有什么区别呢?
发布于 2009-02-13 22:04:51
任何时候您使用非托管代码请求,如流读取器、db请求等;并且您想捕获异常,然后使用try catch 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();
}
如果出现错误,connection对象将被自动处理,但您不能捕获错误
发布于 2009-02-13 21:37:33
因为即使您不处理catch块中的异常,finally也会被执行。
发布于 2013-08-05 18:48:39
最后,即使在返回之后,语句也可以执行。
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
}
https://stackoverflow.com/questions/547791
复制相似问题