Rethrowing Exceptions

You might want your catch block to take some initial corrective action and then rethrow the exception to an outer try block (in a calling function). It might rethrow the same exception, or it might throw a different one. If it throws a different one, it may want to embed the original exception inside the new one so that the calling method can understand the exception history. The InnerException property of the new exception retrieves the original exception.

Because the InnerException is also an exception, it too might have an inner exception. Thus, an entire chain of exceptions can be nested one within the other, much like Ukrainian dolls are contained one within the other. Example 11-8 illustrates.

Example 11-8. Rethrowing and inner exceptions

namespace Programming_CSharp { using System; public class MyCustomException : System.ApplicationException { public MyCustomException( string message,Exception inner): base(message,inner) { } } public class Test { public static void Main( ) { Test t = new Test( ); t.TestFunc( ); } public void TestFunc( ) { try { DangerousFunc1( ); } // if you catch a custom exception // print the exception history catch (MyCustomException e) { Console.WriteLine("\n{0}", e.Message); Console.WriteLine( "Retrieving exception history..."); Exception inner = e.InnerException; while (inner != null) { Console.WriteLine( "{0}",inner.Message); inner = inner.InnerException; } } } public void DangerousFunc1( ) { try { DangerousFunc2( ); } // if ...

Get Programming C#, Second Edition 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.