是否有一种优雅的方法来处理finally块中抛出的异常?
例如:
try {
// Use the resource.
}
catch( Exception ex ) {
// Problem with the resource.
}
finally {
try{
resource.close();
}
catch( Exception ex ) {
// Could not close the resource?
}
}
Run Code Online (Sandbox Code Playgroud)
你如何避免try/ catch在finally街区?
我在理解try-catch-finally的执行顺序时遇到了问题.我见过的所有例子(如:http://stackoverflow.com/questions/4191027/order-of-execution-of-try-catch-and-finally-block)都有一个非常简单的"捕获"部分,打印到控制台.但如果我在捕获中使用"throw"语句会发生什么?
我能想到的最简单的代码可以捕获问题:
public class TestClass
{
void Foo(int num)
{
int answer = 100;
try
{
answer = 100 / num;
}
catch (Exception e)
{
//Probably num is 0
answer = 200;
throw;
}
finally
{
Console.WriteLine("The answer is: " + answer);
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果num == 2,那么输出将是:
答案是:50
但是会为num == 0打印什么?
答案是:100
答案是:200根本
没有印刷......
还是仅仅是一种"未定义的行为"?