Search notes:

C#: catch

Simple example

This simple example will throw a System.DivideByZeroException in the function calc.
Because calc is not guarded with try and catch blocks, the thrown excpetion will be passed to the location of the caller: Console.WriteLine(calc( 0)); in the Main() function.
Main() does have a try and (at least one) catch block. Thus, the type of the thrown execption is used to find the correct catch block. Incidentally, there is a catch-block for the DivideByZeroException excpetion. Thus, execution of the program will be transferred to this block.
using System;

class Prg {

  static int calc(int i) {
     return 42/i;
  }

  static void Main() {

     try {
        Console.WriteLine(calc( 7));
        Console.WriteLine(calc( 0));
        Console.WriteLine(calc(-2));
     }
  //
  // Note the order of the catch blocks:
  //
     catch (DivideByZeroException ex) {
        Console.WriteLine($"Divide by zero excpetion: {ex.Message}");
     }
     catch (Exception ex) {
        Console.WriteLine($"general exception: {ex.Message}");
     }
  }
}
Github repository about-C-Sharp, path: /language/keywords/exception-handling/catch.cs
Note: in this example, the order of the catch-blocks is relevant because System.DivideByZeroException derives from System.Exception. So DivideByZeroException m

See also

throw

Index