【问题标题】:Execution order of try, catch and finally blocktry、catch 和 finally 块的执行顺序
【发布时间】:2017-03-05 02:15:02
【问题描述】:

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

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

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

【问题讨论】:

  • 这似乎是微不足道的测试。
  • 我可以知道你为什么不写一个简单的控制台应用程序来看看会发生什么以及按什么顺序?
  • 抱歉,我是一名初学者,并没有想出自己尝试的想法。在谷歌上搜索后,我找不到答案,所以我决定在这里问。

标签: c# exception-handling try-catch-finally finally try-finally


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    序列永远是

    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

    【讨论】:

    • 对于未捕获的异常也会跳过其余代码。
    【解决方案3】:

    我的问题是,如果不抛出异常,Method3()会在Method4()之前执行吗,

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

    还是finally块只在return、continue或break语句之前执行?

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

    重点

    如果你有这个:

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

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

    不管是否有异常,最终都会被执行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-26
      • 2013-12-30
      • 1970-01-01
      • 2021-05-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多