Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

try-catch

The try-catch statement consists of a try block followed by one or more catch clauses, which specify handlers for different exceptions. This statement takes one of the following forms:

try try-block 
catch (exception-declaration-1) catch-block-1 
catch (exception-declaration-2) catch-block-2 
...
try try-block catch catch-block

where:

try-block
Contains the code segment expected to raise the exception.
exception-declaration, exception-declaration-1, exception-declaration-2
The exception object declaration.
catch-block, catch-block-1, catch-block-2
Contains the exception handler.

Remarks

The try-block contains the guarded code block that may cause the exception. The block is executed until an exception is thrown or it is completed successfully. For example, the following attempt to cast a null object raises the NullReferenceException exception:

object o2 = null;
try
{
   int i2 = (int) o2;   // Error
}

The catch clause can be used without arguments, in which case it catches any type of exception, and referred to as the general catch clause. It can also take an object argument derived from System.Exception, in which case it handles a specific exception. For example:

catch (InvalidCastException e) 
{
}

It is possible to use more than one specific catch clause in the same try-catch statement. In this case, the order of the catch clauses is important because the catch clauses are examined in order. Catch the more specific exceptions before the less specific ones.

A throw statement can be used in the catch block to rethrow the exception, which has been caught by the catch statement. For example:

catch (InvalidCastException e) 
{
   throw (e);   // Rethrowing exception e
}

If you want to rethrow the exception currently handled by a parameterless catch clause, use the throw statement without arguments. For example:

catch
{
   throw;
}

When inside a try block, only initialize variables that are declared therein; otherwise, an exception can occur before the execution of the block is completed. For example, in the following code example, the variable x is initialized inside the try block. An attempt to use this variable outside the try block in the Write(x) statement will generate the compiler error: Use of unassigned local variable.

public static void Main() 
{
   int x;
   try 
   {
      x = 123;   //   Don't do that.
      // ...
   }
   catch
   {
      // ...
   }
   Console.Write(x);   // Error: Use of unassigned local variable 'x'.
}

For more information on catch, see try-catch-finally.

Example

In this example, the try block contains a call to the method MyFn() that may cause an exception. The catch clause contains the exception handler that simply displays a message on the screen. When the throw statement is called from inside MyFn(), the system looks for the catch statement and displays the message Exception caught.

// Rethrowing exceptions:
using System;
class MyClass 
{
   public static void Main() 
   {
      MyClass x = new MyClass();
      try 
      {
         string s = null;
         x.MyFn(s);
      }

      catch (Exception e)
      {
         Console.WriteLine("{0} Exception caught.", e);
      }
   }

   public void MyFn(string s) 
   {
      if (s == null)
         throw(new ArgumentNullException());
   }   
}

Output

The following exception occurs:

System.ArgumentNullException

Example

In this example, two catch statements are used. The most specific exception, which comes first, is caught.

// Ordering catch clauses
using System;
class MyClass 
{
   public static void Main() 
   {
      MyClass x = new MyClass();
      try 
      {
         string s = null;
         x.MyFn(s);
      }

      // Most specific:
      catch (ArgumentNullException e) 
      {
         Console.WriteLine("{0} First exception caught.", e);
      }

      // Least specific:
      catch (Exception e) 
      {
         Console.WriteLine("{0} Second exception caught.", e);
      }

   }

   public void MyFn(string s) 
   {
      if (s == null) 
         throw new ArgumentNullException();
   }   
}

Output

The following exception occurs:

System.ArgumentNullException

In the preceding example, if you start with the least specific catch clause, you will get the error message:

A previous catch clause already catches all exceptions of this or a super type ('System.Exception')

However, to catch the least specific exception, replace the throw statement by the following one:

throw new Exception();

See Also

C# Keywords | Compare to C++ | Exception Handling Statements | throw | try-finally | Throwing Exceptions | C. Grammar

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft