Roe*_*rel -2 c# 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根本
没有印刷......
还是仅仅是一种"未定义的行为"?
如果try块内发生异常,则执行catch块内的代码.如果您有多个catch块,则最好匹配捕获的异常.
class A : System.Exception {}
class B : A {}
void Test()
{
try
{
throw new B();
}
catch (A a)
{
//as B is derived from A, this catch block will be invoked.
}
catch (Exception e)
{
}
}
Run Code Online (Sandbox Code Playgroud)
毕竟,块执行完毕.是否发生异常并不重要.
[编辑] 澄清订单多一点(感谢评论)
void Test()
{
Debug.WriteLine("1");
try
{
Debug.WriteLine("2");
throw new Exception();
Debug.WriteLine("3");
}
catch
{
Debug.WriteLine("4");
throw;
Debug.WriteLine("5");
}
finally
{
Debug.WriteLine("6");
}
Debug.WriteLine("7");
}
Run Code Online (Sandbox Code Playgroud)
将打印的是:
1 2 4 6
3是不打印的,因为它之前会抛出异常.因为throw捕获块中没有打印相同的5. 7 .
[/编辑]
所以回答你的问题:答案是:200