How to: Catch an Exception

This example uses try-catch blocks to catch division by zero as an exception. After the exception is caught, the execution is resumed in the finally block.

Example

int top = 0, bottom = 0, result = 0;

try
{
    result = top / bottom;
}
catch (System.Exception ex)
{
    System.Console.WriteLine("{0} exception caught here.", ex.GetType().ToString());
    System.Console.WriteLine(ex.Message);
}
finally
{
    System.Console.WriteLine("Clean-up code executes here...");
}
System.Console.WriteLine("Program execution continues here...");

System.DivideByZeroException exception caught here. Attempted to divide by zero. Clean-up code executes here... Program execution continues here...

Compiling the Code

Copy the code and paste it into the Main method of a console application.

See Also

Other Resources

Visual C# Express