try,catch和finally块的执行顺序

ser*_*us6 1 c# exception-handling finally try-catch-finally try-finally

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

try {
    Method1();
}
catch(...) {
    Method2();
}
finally {
    Method3();
}
Method4();
return;
Run Code Online (Sandbox Code Playgroud)

我的问题是,只要没有异常被抛出,将方法3()方法4将()之前执行呢,还是该finally块只有之前执行return,continue或break声明?

Rio*_*ams 5

是的,将按照您的预期按顺序执行finally块try-catch,然后执行将继续执行其余代码(在完成整个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)
Run Code Online (Sandbox Code Playgroud)

例

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

您可以在此处看到此示例,其中包含以下输出:

1
2
3
4
Run Code Online (Sandbox Code Playgroud)