小编Ser*_*kov的帖子

在 C# 中传播在 finally 块中抛出的异常而不丢失来自 catch 块的异常的最佳实践是什么?

当一个异常可能在 finally 块中抛出时如何传播这两个异常 - 从 catch 和 from 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;
            }
        }
    }
} …
Run Code Online (Sandbox Code Playgroud)

c# exception-handling try-catch-finally

6
推荐指数
1
解决办法
1463
查看次数

标签 统计

c# ×1

exception-handling ×1

try-catch-finally ×1