If an exception can be thrown in the finally block, how can both exceptions be thrown - from catch, and finally?
As a possible solution, use an 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; } } } }
These exceptions can be handled as in the following snippet:
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(); }
, " " . , , , . , ( "" , . , , - OutOfMemoryException, , , , boned: -)
finally try, , . , , , AggregateException . , , , ().