如果可能在finally块中引发异常,如何传播这两个异常 - 从catch和finally?C#中传播抛出finally块的异常而不丢失catch块的异常的最佳做法是什么?
作为一个可能的解决方案 - 使用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();
}
我想不出一个有意义的场景,它有必要知道这两个例外。你的解决方案肯定会工作,但在调用者处理它将非常复杂。 – dasblinkenlight
我认为在最后(在finally catch块中)重新抛出永远不会被达到,因为如果发生异常,对象* e *永远不会* null *。 – pasty
如果您遇到异常情况,您说“我知道如何解决这个问题” - 如果事实证明您不知道如何解决此问题,那么您需要尽可能少地做以掩盖错误情况。 –