Exception Propagation in C#


Exception Propogation can be understood by how exception handling works in C#.

In try, when an exception occurs the corresponding catch blocks are checked. This is done to see if they can catch the exception. If no matching exception is found, the exception is propagated to a higher-level try block. This repeats until the exception is caught. In case, the exception isn’t caught, the execution of the program comes to an end.

The above concept is explain in the below example showing nested try statements.

Example

 Live Demo

using System;
using System.Text;
public class Demo {
   public static void Main() {
      try {
         try {
            throw new ArgumentException();
         }catch (NullReferenceException e) {
            Console.WriteLine("catch one");
         } finally {
            Console.WriteLine("finally one");
         }
      } catch (Exception e) {
         Console.WriteLine("catch two");
      } finally {
         Console.WriteLine("finally two");
      }
      Console.ReadLine();
   }
}

Output

finally one
catch two
finally two

Updated on: 23-Jun-2020

603 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements