Compartilhar via


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