try、catch、finally block的执行顺序

Execution order of try, catch and finally block

假设我有这样的 C# 代码:

try {
    Method1();
}
catch(...) {
    Method2();
}
finally {
    Method3();
}
Method4();
return;

我的问题是,如果不抛出异常,Method3()会在Method4()之前执行,还是finally块只在returncontinuebreak 语句?

是的,try-catchfinally 块将按照您预期的顺序执行,然后执行其余代码(在完成整个 try-catch-finally块)。

您可以将整个 try-catch-finally 块视为一个单独的组件,其功能与任何其他方法调用一样(代码在其前后执行)。

// Execute some code here

// try-catch-finally (the try and finally blocks will always be executed
// and the catch will only execute if an exception occurs in the try)

// Continue executing some code here (assuming no previous return statements)

例子

try 
{
    Console.WriteLine("1");
    throw new Exception();
}
catch(Exception) 
{
    Console.WriteLine("2");
}
finally 
{
    Console.WriteLine("3");
}
Console.WriteLine("4");
return;

您可以 see an example of this in action here 产生以下输出:

1
2
3
4

顺序总是

try 
--> catch(if any exception occurs) 
--> finally (in any case) 
--> rest of the code (unless the code returns or if there is any uncaught exceptions from any of the earlier statements)

有用的资源:https://msdn.microsoft.com/en-us/library/zwc8s4fz.aspx

My question is, provided no exception is thrown, will Method3() be executed before Method4(),

是的,Method3会在Method4之前执行,因为无论是否抛出异常,都会执行到finally块,然后从那里继续。

or is it that the finally block is only executed before a return, continue or break statement?

不是,不管有没有异常,总是在try块之后执行。

重点

如果你有这个:

try 
{
    DoOne();
    DoTwo();
    DoThree();
}
catch{ // code}
finally{ // code}

如果 DoOne() 抛出异常,则永远不会调用 DoTwo()DoThree()。因此,不要认为整个 try 块总是会被执行。实际上,只有抛出异常之前的部分会被执行,然后执行到catch块。

finally会一直执行-不管是否有异常。