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:
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.