Catching the Exception Object Farther up the Function Call Chain

As mentioned previously, an exception object travels up the function call chain until it finds a matching catch block. Consequently, it is possible to catch an exception object thrown in one function (like Method2) in a different function farther up the calling chain (like Method1). This is demonstrated in Listing 19.3, where the try-catch blocks of Method2 in Listing 19.2 have been moved to Method1. So, instead of enclosing the divide by zero statement as in the previous listing, the try block in lines 19–24 now encloses the call to Method2 in line 22.

Listing 19.3. CaughtInOtherFunction.cs
 01: using System; 02: 03: class MyClass 04: { 05: public static void Main() 06: { 07: ...

Get C# Primer Plus 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.