Udostępnij za pośrednictwem


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. When an exception is thrown, the common language runtime (CLR) looks for the catch statement that handles this exception. If the currently executing method does not contain such a catch block, the CLR looks at the method that called the current method, and so on up the call stack. If no catch block is found, then the CLR displays an unhandled exception message to the user and stops execution of the program.

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
}

Although the catch clause can be used without arguments to catch any type of exception, this usage is not recommended. In general, you should only catch those exceptions that you know how to recover from. Therefore, you should always specify an object argument derived from System.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. The compiler will produce an error if you order your catch blocks so that a later block will never be reached.

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
}

You can also throw a new exception. When you do this, specify the exception you catch as the inner exception:

catch (InvalidCastException e) 
{
   // Can do cleanup work here.
    throw new CustomException("Error message here.", 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 about catch, see try-catch-finally.

Example

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

class TryFinallyTest
{
    static void ProcessString(string s)
    {
        if (s == null)
        {
            throw new ArgumentNullException();
        }
    }

    static void Main()
    {
        string s = null; // For demonstration purposes. 

        try
        {            
            ProcessString(s);
        }

        catch (Exception e)
        {
            Console.WriteLine("{0} Exception caught.", e);
        }
    }
}
    /*
    Output:
    System.ArgumentNullException: Value cannot be null.
       at TryFinallyTest.Main() Exception caught.
     * */

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

class ThrowTest3
{
    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);
        }
    }
}
/*
 Output:
System.ArgumentNullException: Value cannot be null.
   at TryFinallyTest.Main() First exception caught.
*/

In the previous 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

Concepts

C# Programming Guide

Reference

C# Keywords

The try, catch, and throw Statements

Exception Handling Statements (C# Reference)

throw (C# Reference)

try-finally (C# Reference)

Other Resources

C# Reference