5.5. Assuring Exceptions are Not Lost when Using Finally Blocks
Problem
You have multiple nested
try
/catch
,
try
/finally
, and
try
/catch
/finally
blocks. If a catch
block attempts to rethrow an
exception, it is possible that the rethrown exception could get
discarded and a new and unexpected exception could be caught by an
outer exception handler. You want to prevent this situation from
occurring.
Solution
Add an inner
try
/catch
block in the
finally
block of the outer exception
handler:
private void PreventLossOfException( ) { try { //... } catch(Exception e) { Console.WriteLine("Error message == " + e.Message); throw; } finally { try { //... } catch(Exception e) { Console.WriteLine(@"An unexpected error occurred in the finally block. Error message == " + e.Message); } } }
This block will prevent the original exception from being lost.
Discussion
Consider what would happen if an error were thrown from the inner
finally
block contained in the
ReThrowException
method. If the code looked like
this:
public void PreventLossOfException( ) { try { Console.WriteLine("In outer try"); ReThrowException( ); } catch(Exception e) { Console.WriteLine("In outer catch. ReThrown error == " + e.Message); } finally { Console.WriteLine("In outer finally"); } } private void ReThrowException( ) { try { Console.WriteLine("In inner try"); int z2 = 9999999; checked{z2 *= 999999999;} } catch(OverflowException ofe) { Console.WriteLine("An Overflow occurred. Error message == " + ofe.Message); throw; } catch(Exception ...
Get C# Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.