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 exception 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

Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error: 8 attempt to write a readonly database in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php:78 Stack trace: #0 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(78): PDOStatement->execute(Array) #1 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(30): insert_webrequest_('/notes/developm...', 1759405899, '216.73.216.42', 'Mozilla/5.0 App...', NULL) #2 /home/httpd/vhosts/renenyffenegger.ch/httpsdocs/notes/development/languages/C-Sharp/language/keywords/exception-handling/catch(78): insert_webrequest() #3 {main} thrown in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php on line 78