【问题标题】:Weird flow control code奇怪的流量控制代码
【发布时间】:2017-01-06 00:22:58
【问题描述】:

我是一名 C++ 开发人员,正在研究一些他不理解的 C#。代码的格式基本是:

bool method (params)
{
    ...
    try
    {
         Do Some Stuff with some manual throws and some method calls;
    }
    catch (Exception e)
    {
     if (e is SomeSpecificTypeOfException)
          throw e;
     else
          return false;
    }
    finally
    {
         Do Some More Stuff;
    }
    ...
    return true;
}

我应该如何解释这段代码?开发人员说他从未见过这种类型的用法,但可能“总是在退出方法之前执行 finally”,这意味着 catch then rethrow 在将 e 抛到它上面之前执行 finally 并且 catch/return 在到达结束后返回 false最后。这是正确的吗?

【问题讨论】:

  • 是的,finally 总是在退出方法之前执行(无论是通过return 还是throw)。
  • 这里是异常处理文档的链接:msdn.microsoft.com/en-us/library/ms173162.aspx
  • 重要的是要注意,像这样重新抛出 e 会破坏你的堆栈跟踪,最好有 throw; 保留堆栈跟踪。

标签: c# exception flow


【解决方案1】:

如果在尝试中出现问题,它将执行捕获。 finally 总是执行。

https://msdn.microsoft.com/en-us/library/dszsf989.aspx

【讨论】:

    【解决方案2】:

    嗯,C# 中的finally 在某种程度上类似于 C++ 中基于堆栈的对象的析构函数,当抛出异常时会自动调用。

    或者,

    try { a; } 
    catch { b; }   // Might have multiple catches...
    finally { c; }
    

    本质上等同于:

    try
    {
        try { a; } 
        catch { b; }  // All catch clauses would be here...
    }
    catch
    {
         c;      // code that was in finally block.
         throw;  // rethrow same exception
    }
    

    在 C++ 中,可以编写如下代码:

    class Cleaner { ~Cleaner() { c(); } };
    
    void method() 
    {
        Cleaner cleaner;
        try { a(); }
        catch(...) { b(); }
    
        // Thus c(); would be executed before leaving method
     }
    

    显然,这可以通过 lambdas 变得更通用...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-24
      • 2014-02-21
      • 1970-01-01
      • 1970-01-01
      • 2023-04-01
      • 1970-01-01
      相关资源
      最近更新 更多