C# catch Clause

Description

A catch clause specifies what type of exception to catch.

Example

The type must either be System.Exception or a subclass of System.Exception. Catching System.Exception catches all possible errors. You also catch specific exception types.

You can handle multiple exception types with multiple catch clauses:


using System;/*w w w  .j  a va 2 s. c om*/
class Test
{
     static void Main (string[] args)
     {
           try
           {
             byte b = byte.Parse (args[0]);
             Console.WriteLine (b);
           }
           catch (IndexOutOfRangeException ex)
           {
             Console.WriteLine ("Please provide at least one argument");
           }
           catch (FormatException ex)
           {
             Console.WriteLine ("That's not a number!");
           }
           catch (OverflowException ex)
           {
             Console.WriteLine ("You've given me more than a byte!");
           }
     }
}

The code above generates the following result.

Catch general exception type

An exception can be caught without specifying a variable if you don't need to access its properties:


catch (StackOverflowException)   // no variable
{
   ...
}

Furthermore, you can omit both the variable and the type (meaning that all exceptions will be caught):


catch { ... }

Example 2


using System; //from www  .  jav  a2s  .  c  om
 
class MainClass { 
  public static void Main() { 
    int[] numer = { 4, 8, 16}; 
    int j=0;
    
    for(int i=0; i < 10; i++) { 
      try { 
        Console.WriteLine(numer[i] + " / " + 
                           numer[i] + " is " + 
                           numer[i]/j); 
      } 
      catch (DivideByZeroException) { 
        // catch the exception 
        Console.WriteLine("Can't divide by Zero!"); 
      } 
      catch (IndexOutOfRangeException) { 
        // catch the exception 
        Console.WriteLine("No matching element found."); 
      } 
    } 
  } 
}

The code above generates the following result.

Example 3


using System; /*  w  ww .  j  a v  a 2 s.  c  o m*/
 
class MainClass { 
  public static void Main() { 
    int[] numer = { 4, 8}; 
    int d = 0;
    
    for(int i=0; i < 10; i++) { 
      try { 
        Console.WriteLine(numer[i] + " / " + 
                           numer[i] + " is " + 
                           numer[i]/d); 
      } 
      catch { 
        Console.WriteLine("Some exception occurred."); 
      } 
    } 
  } 
}

The code above generates the following result.





















Home »
  C# Tutorial »
    C# Language »




C# Hello World
C# Operators
C# Statements
C# Exception