C# try Statements and Exceptions

Description

A try statement specifies a code block subject to error-handling or cleanup code.

The try block must be followed by a catch block, a finally block, or both.

The catch block executes when an error occurs in the try block. The finally block performs cleanup code, whether or not an error occurred.

Syntax

A try statement looks like this:


try/*w  w  w .  ja v  a  2  s  .c om*/
{
  ... // exception may get thrown within execution of this block
}
catch (ExceptionA ex)
{
  ... // handle exception of type ExceptionA
}
catch (ExceptionB ex)
{
  ... // handle exception of type ExceptionB
}
finally
{
  ... // cleanup code
}

Example

Consider the following program. Because x is zero, the runtime throws a DivideByZeroException, and our program terminates. We can prevent this by catching the exception as follows:


using System;//from w w w. j  a  v a 2  s.  co m

class Test
{
  static int Calc (int x) { return 10 / x; }

  static void Main()
  {
    try
    {
      int y = Calc (0);
      Console.WriteLine (y);
    }
    catch (DivideByZeroException ex)
    {
      Console.WriteLine ("x cannot be zero");
    }
    Console.WriteLine ("program completed");
  }
}

The code above generates the following result.

Example 2


using System; //from   w  w  w  .j  a  v  a  2 s. c o m
 
class MainClass { 
  public static void Main() { 
    int[] numer = { 4, 8, 16, 32, 64, 128, 256, 512 }; 
    int d = 0;
 
    try { // outer try 
      for(int i=0; i < 10; i++) { 
        try { // nested try 
          Console.WriteLine(numer[i] + " / " + 
                             numer[i] + " is " + 
                             numer[i]/d); 
        } 
        catch (DivideByZeroException) { 
          // catch the exception 
          Console.WriteLine("Can't divide by Zero!"); 
        } 
      } 
    }  
    catch (IndexOutOfRangeException) { 
      // catch the exception 
      Console.WriteLine("No matching element found."); 
      Console.WriteLine("Fatal error -- program terminated."); 
    } 
  } 
}

The code above generates the following result.





















Home »
  C# Tutorial »
    C# Language »




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