C# Language Reference
try-catch (C# Reference)

The try-catch statement consists of a try block followed by one or more catch clauses, which specify handlers for different exceptions.

Remarks

The try block contains the guarded code 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 re-throw the exception, which has been caught by the catch statement. For example:

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

If you want to re-throw the exception currently handled by a parameter-less 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.

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

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

Example

In this example, the try block contains a call to the method MyMethod() 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 MyMethod, the system looks for the catch statement and displays the message Exception caught.

// try_catch_example.cs
using System;
class MainClass
{
    static void ProcessString(string s)
    {
        if (s == null)
        {
            throw new ArgumentNullException();
        }
    }
    
    static void Main()
    {
        try
        {
            string s = null;
            ProcessString(s);
        }
        catch (Exception e)
        {
            Console.WriteLine("{0} Exception caught.", e);
        }
    }
}

Sample Output

System.ArgumentNullException: Value cannot be null.
   at MainClass.Main() Exception caught.

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

// try_catch_ordering_catch_clauses.cs
using System;
class MainClass
{
    static void ProcessString(string s)
    {
        if (s == null)
        {
            throw new ArgumentNullException();
        }
    }

    static void Main()
    {
        try
        {
            string s = null;
            ProcessString(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);
        }
    }
}

Sample Output

System.ArgumentNullException: Value cannot be null.
   at MainClass.Main() First exception caught.
Comments

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();

C# Language Specification

For more information, see the following sections in the C# Language Specification:

  • 5.3.3.13 Try-catch statements

  • 8.10 The try statement

  • 16 Exceptions

See Also

Tasks

How to: Explicitly Throw Exceptions

Reference

C# Keywords
The try, catch, and throw Statements
Exception Handling Statements (C# Reference)
throw (C# Reference)
try-finally (C# Reference)

Concepts

C# Programming Guide

Other Resources

C# Reference

Tags :


Community Content

Peter Ritchie
Exception throwing guidelines.

While the above is a pedantic example of how to use try/catch, it is not recommended to "handle" the type Exception.  There are many reasons to avoid handling Exception type:

  • It hides bugs
    By not producing any error to the user you don't give them any feedback that anything is wrong and therefore the existence of the bug does not manifest immediately.
  • Handling all exceptions without exception-specific handling logic will leave the application in an unknown state.
    The exception was thrown for a reason.  If you don't know how to handle it then you don't know the consequences of the exception that occurred.  Those consequences may leave the application in an unknown state that will affect subsequent processing, ending up with the above--hidden bugs.
  • It circumvents higher-level exception handling.
    A higher-level exception handler may know exactly what to do with a certain type of exception; possibly much better than your code.  By using catch(Exception) you circumvent that and end up with the above--the application may be in a unknown state.

"Handling" and "catching"

"Handling" an exception is the process of catching an exception and not rethrowing the exact caught exception.  It is quite permissible to perform clean-up code in the event something went wrong, which could be as simple as:

try
{
//...
}
catch(Exception)
{
    file.Close();
    throw; // rethrow the exact exception
}

With languages that support the "finally" keyword this is generally not necessary.

When to handle "Exception"

In a top-level, or last-chance, exception handler (one where catch is the last statement before termination of the application), it is safe to "handle" the exception when logging uncaught exceptions, there is a need to provide a more user-friendly message, or application-specific information needs not to be displayed.  For example

/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
    try
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new MainForm());
    }
    catch (Exception e)
    {
        System.Diagnostics.Trace.WriteLine(e.ToString());
        MessageBox.Show("An fatal error in the application occured and it had to be terminated");
    }
}

General exception handling guidelines

  • Do not catch general exception types like System.Exception and System.SystemException
  • Choose exceptions over error codes.
  • Do not use exception handling for flow of control, only for failure situations.
  • Document all exceptions thrown by a publicly callable members. (see exception element in XML documentation comments).
  • Do not have publicly callable members throw or not throw based upon a parameter.
  • Do you use exceptions as return values or out parameters (this is an error code).
  • Avoid throwing exceptions from finally blocks.
  • Avoid throwing exceptions from constructors.
  • Do not rethrow by throwing the same exception object.  This causes the stack trace for the original exception to be lost--use a lone "throw;" statement (without an object following it) to "rethrow" a catch exception.

References

.NET Framework Developer's Guide: Catching and Throwing Standard Exception Types[http://msdnwiki.microsoft.com/en-us/mtpswiki/ms229007.aspx]

Visual Studio Team System Code Analysis: Do not catch general exception types [http://msdn2.microsoft.com/en-us/library/ms182137.aspx]

FxCop FAQ: Why does FxCop warn against catch(Exception)? discussions[http://blogs.msdn.com/fxcop/archive/2006/06/14/631923.aspx]

Exception handling guidelines [http://blogs.msdn.com/ericgu/archive/2006/02/15/532615.aspx]

Exception Throwing [http://blogs.msdn.com/kcwalina/archive/2005/03/16/396787.aspx]

Tags :

Page view tracker