C# 异常处理 - 最后一个 catch 块获取是否会重新抛出异常?

C# Exception Handling - will last catch block fetch re-thrown Exception?

我想知道这段代码是否会以重试 10 次后调用 CleanUp() 的方式工作?还是 throw new Exception() 不会被最后一个 catch 块捕获?

public void Process()
{
    try
    {}
    catch (MyException e)
    {           
        int retries = GetRetries();
        if(retries > 10)
        {
            _logger.LogError("Retried event already {retries} times. Giving up.", retries);
            throw new Exception("Giving up!");
        }

        Process();

    }
    catch (Exception e)
    {
        CleanUp();
    }
}

不,不是那样的。对于任何给定的 try/catch 块,相应的 catch 块只能捕获源自 try 的异常。 catch 块内抛出的异常不会被同一级别的其他 catch 块捕获。

finally 块允许您在控件因 any 原因离开 try/catch 时编写 运行 代码。因此,如果 try 的末尾已经有一个 CleanUp,那么您只需将最后的 catch(Exception e) 更改为 finally 并删除 CleanUp 末尾的 CleanUp try部分。

但是,如果您只想 运行 CleanUp 当控制离开 try/catch 通过异常 ,你就没那么幸运了。 IL 中有一个 fault 子句,即 finally,但仅用于异常,但在 C# 中未公开。

所以如果你需要它,通常最好引入一个额外的 bool 来表明你无一例外地到达了 try 块的末尾,并使用它来使你的 CleanUpfinally.

中有条件地调用

或者您可以通过嵌套 try/catch 块来模拟 try/catch/fault:

try
{
    try
    {}
    catch (MyException e)
    {           
        int retries = GetRetries();
        if(retries > 10)
        {
            _logger.LogError("Retried event already {retries} times. Giving up.", retries);
            throw new Exception("Giving up!");
        }

        Process();

    }
}
catch
{
  //Act as fault
  CleanUp();
  throw;
}