C# 中的最佳实践是什么,可以传播在 finally 块中引发的异常,而不会丢失 catch 块中的异常

本文关键字:异常 catch 最佳 是什么 传播 finally | 更新日期: 2023-09-27 18:36:11

当可以在 finally 块中抛出异常时,如何传播两个异常 - 从 catch 和从 finally ?

作为一种可能的解决方案 - 使用 AggregateException:

internal class MyClass
{
    public void Do()
    {
        Exception exception = null;
        try
        {
            //example of an error occured in main logic
            throw new InvalidOperationException();
        }
        catch (Exception e)
        {
            exception = e;
            throw;
        }
        finally
        {
            try
            {
                //example of an error occured in finally
                throw new AccessViolationException();
            }
            catch (Exception e)
            {
                if (exception != null)
                    throw new AggregateException(exception, e);
                throw;
            }
        }
    }
}

可以像以下代码片段中这样处理这些异常:

private static void Main(string[] args)
{
    try
    {
        new MyClass().Do();
    }
    catch (AggregateException e)
    {
        foreach (var innerException in e.InnerExceptions)
            Console.Out.WriteLine("---- Error: {0}", innerException);
    }
    catch (Exception e)
    {
        Console.Out.WriteLine("---- Error: {0}", e);
    }
    Console.ReadKey();
}

C# 中的最佳实践是什么,可以传播在 finally 块中引发的异常,而不会丢失 catch 块中的异常

我经常遇到同样的情况,还没有找到更好的解决方案。但我认为OP建议的解决方案是合格的。

以下是对原始示例的轻微修改:

internal class MyClass
{
    public void Do()
    {
        bool success = false;
        Exception exception = null;
        try
        {
            //calling a service that can throw an exception
            service.Call();
            success = true;
        }
        catch (Exception e)
        {
            exception = e;
            throw;
        }
        finally
        {
            try
            {
                //reporting the result to another service that also can throw an exception
                reportingService.Call(success);
            }
            catch (Exception e)
            {
                if (exception != null)
                    throw new AggregateException(exception, e);
                throw;
            }
        }
    }
}

恕我直言,在这里忽略一个或另一个例外将是致命的。

另一个

例子:想象一个校准设备(DUT)的测试系统,因此必须控制另一个向DUT发送信号的设备。

internal class MyClass
{
    public void Do()
    {
        Exception exception = null;
        try
        {
            //perform a measurement on the DUT
            signalSource.SetOutput(on);
            DUT.RunMeasurement();
        }
        catch (Exception e)
        {
            exception = e;
            throw;
        }
        finally
        {
            try
            {
                //both devices have to be set to a valid state at end of the procedure, independent of if any exception occurred
                signalSource.SetOutput(off);
                DUT.Reset();
            }
            catch (Exception e)
            {
                if (exception != null)
                    throw new AggregateException(exception, e);
                throw;
            }
        }
    }
}

在此示例中,重要的是在该过程之后将所有设备设置为有效状态。但是这两种设备也可以在 finally 块中抛出异常,这些异常不能丢失或忽略。

关于调用者的复杂性,我也没有看到任何问题。例如,当使用 System.Threading.Tasks 时,WaitAll() 方法也可以抛出必须以相同方式处理的 AgregateExceptions。

关于@damien的评论还有一个注意事项:捕获异常只是为了将其包装到 AggregateException 中,以防 finally 块抛出。除例外情况外,不会执行任何其他操作,也不会以任何方式进行处理。

对于那些想要走这条路的人,你可以使用我最近创建的一个小帮助程序类:

public static class SafeExecute
{
    public static void Invoke(Action tryBlock, Action finallyBlock, Action onSuccess = null, Action<Exception> onError = null)
    {
        Exception tryBlockException = null;
        try
        {
            tryBlock?.Invoke();
        }
        catch (Exception ex)
        {
            tryBlockException = ex;
            throw;
        }
        finally
        {
            try
            {
                finallyBlock?.Invoke();
                onSuccess?.Invoke();
            }
            catch (Exception finallyBlockException)
            {
                onError?.Invoke(finallyBlockException);
                // don't override the original exception! Thus throwing a new AggregateException containing both exceptions.
                if (tryBlockException != null)
                    throw new AggregateException(tryBlockException, finallyBlockException);
                // otherwise re-throw the exception from the finally block.
                throw;
            }
        }
    }
}

并像这样使用它:

public void ExecuteMeasurement(CancellationToken cancelToken)
{
    SafeExecute.Invoke(
        () => DUT.ExecuteMeasurement(cancelToken),
        () =>
        {
            Logger.Write(TraceEventType.Verbose, "Save measurement results to database...");
            _Db.SaveChanges();
        },
        () => TraceLog.Write(TraceEventType.Verbose, "Done"));
}

正如评论所暗示的那样,这可能表明"不幸"结构化代码。 例如,如果您经常发现自己处于这种情况,则可能表明您试图在方法中做太多事情。 你只想抛出和异常,如果你没有其他事情可以做(你的代码被一个你无法编程的问题"卡住"。 只有当有合理的期望可以做一些有用的事情时,你才想捕捉到异常。 框架中有一个 OutOfMemoryException,但你很少会看到人们试图抓住它,因为在大多数情况下,这意味着你很痛苦:-)

如果 finally 块中的异常是 try 块中异常的直接结果,则返回该异常只会使实际问题复杂化或模糊,使其更难解决。 在极少数情况下,如果存在返回的验证原因(例如异常),则使用 AggregateException 将是执行此操作的方法。 但在采用这种方法之前,请问问自己是否可以将异常分成单独的方法,在这些方法中可以(单独)返回和处理单个异常。