最终块中的任何内容总是(几乎)执行,那么将代码封装到其中还是不封闭到底有什么区别?
最终块中的任何内容总是(几乎)执行,那么将代码封装到其中还是不封闭到底有什么区别?
Answers:
无论是否存在异常,finally块中的代码都将被执行。当涉及某些家政功能时,这非常方便,您需要始终像关闭连接一样运行。
现在,我猜您的问题是为什么您应该这样做:
try
{
doSomething();
}
catch
{
catchSomething();
}
finally
{
alwaysDoThis();
}
当您可以这样做时:
try
{
doSomething();
}
catch
{
catchSomething();
}
alwaysDoThis();
答案是很多时候,catch语句中的代码要么抛出异常,要么脱离当前函数。对于后面的代码,“ alwaysDoThis();” 如果catch语句中的代码发出返回或引发新异常,则调用将不会执行。
已经指出了使用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).
}
这种行为使它在各种情况下都非常有用,特别是当您需要执行清理(处置资源)时,尽管 在这种情况下使用using块通常会更好。
每当您使用非托管代码请求(例如流读取器,数据库请求等)时;并且您想捕获异常,然后使用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();
}
如果有错误,连接对象将被自动处理,但是您不会捕获该错误
即使返回,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
}
finally
,如:
try {
// do something risky
} catch (Exception ex) {
// handle an exception
} finally {
// do any required cleanup
}
是您执行后保证执行代码的机会 try..catch
无论您的try块是否引发异常,这都是块。
这使其非常适合发布资源,数据库连接,文件句柄等。
我将解释在文件读取器异常示例中finally的使用
try{ StreamReader strReader = new StreamReader(@"C:\Ariven\Project\Data.txt"); Console.WriteLine(strReader.ReadeToEnd()); StreamReader.Close(); } catch (Exception ex) { Console.WriteLine(ex.Message); }
在上面的示例中,如果缺少名为Data.txt的文件,则将引发并处理异常,但将永远不会执行被调用的语句。因此,与阅读器相关的资源从未发布。StreamReader.Close();
StreamReader strReader = null; try{ strReader = new StreamReader(@"C:\Ariven\Project\Data.txt"); Console.WriteLine(strReader.ReadeToEnd()); } catch (Exception ex){ Console.WriteLine(ex.Message); } finally{ if (strReader != null){ StreamReader.Close(); } }
快乐编码:)
注意: “ @”用于创建逐字字符串,以避免出现“无法识别的转义序列”错误。@符号表示从字面上读取该字符串,否则不解释控制字符。
有时,您不想处理异常(没有catch块),但是您希望执行一些清理代码。
例如:
try
{
// exception (or not)
}
finally
{
// clean up always
}