C# try Statements and Exceptions

In this chapter you will learn:

  1. What are C# try Statements and Exceptions
  2. Syntax for try statement
  3. Example for try statement
  4. Use a nested try block

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  o  m
{
  ... // 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;/*  w  ww . ja  v  a 2  s.  c o 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 .ja  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.

Next chapter...

What you will learn in the next chapter:

  1. What is catch clause
  2. Example catch statement
  3. Catch general exception type
  4. Use multiple catch statements
  5. Use the 'catch all' catch statement
Home »
  C# Tutorial »
    C# Language »
      C# Exception
C# Exception
C# Exception classes
C# try Statements and Exceptions
C# catch Clause
C# finally Block
C# throw statement
C# System Exception