try-catch Statement

The try statement defines a block of code to which exception handling blocks (catch and finally) can be attached. The catch statement defines a block of code that is run if an exception is thrown in the try block. The finally statement defines a block of code that is run whether or not an exception is thrown in the try block.

Syntax


[label:]
try
{
    // Statements to execute.
    statement_list
}
catch [ (ExceptionType name) ]
{
    // Statements to execute when exception of type ExceptionType is thrown.
    statement_list
}
[ ... ]
[ finally
{
    // Statements to execute.
    statement_list
} ]
                

Remarks

An exception is an event that occurs during the execution of a program that disrupts the normal flow of the program's instructions. The try statement allows you to detect and manage runtime errors without terminating the program.

The try Block

The code that might throw an exception is placed inside the try block.

The catch Block

If an exception occurs within the try block, the execution jumps to the first catch block that matches the type of the exception thrown. If no matching catch block is found, the exception propagates up the call stack.

You can specify the type of exception to catch. If you omit the exception type, the catch block will catch any exception. It is good practice to catch specific exceptions rather than all exceptions.

Catching specific exceptions


try
{
    // Code that might throw an exception
    int result = 10 / 0;
}
catch (DivideByZeroException ex)
{
    Console.WriteLine("Cannot divide by zero.");
    Console.WriteLine($"Details: {ex.Message}");
}
catch (Exception ex)
{
    Console.WriteLine("An unexpected error occurred.");
    Console.WriteLine($"Details: {ex.Message}");
}
                

Catching any exception


try
{
    // Code that might throw an exception
    object obj = null;
    Console.WriteLine(obj.ToString());
}
catch
{
    Console.WriteLine("An error occurred.");
}
                

The finally Block

The finally block is optional. The statements in the finally block are always executed, regardless of whether an exception was thrown or caught. This is useful for releasing resources such as file handles or database connections.

Using finally for resource management


System.IO.StreamReader reader = null;
try
{
    reader = new System.IO.StreamReader("myFile.txt");
    string content = reader.ReadToEnd();
    Console.WriteLine(content);
}
catch (System.IO.FileNotFoundException)
{
    Console.WriteLine("The file was not found.");
}
finally
{
    if (reader != null)
    {
        reader.Close();
        Console.WriteLine("File stream closed.");
    }
}
                

The using Statement (Recommended)

For resources that implement the IDisposable interface (like file streams), the using statement is a more concise and safer way to ensure that resources are disposed of correctly, even if exceptions occur.


try
{
    using (System.IO.StreamReader reader = new System.IO.StreamReader("myFile.txt"))
    {
        string content = reader.ReadToEnd();
        Console.WriteLine(content);
    } // The reader is automatically disposed here
}
catch (System.IO.FileNotFoundException)
{
    Console.WriteLine("The file was not found.");
}
                

Examples

Example 1: Basic try-catch


public class ExceptionDemo
{
    public static void Main(string[] args)
    {
        try
        {
            Console.WriteLine("Entering try block.");
            int num1 = 10;
            int num2 = 0;
            int result = num1 / num2; // This will throw DivideByZeroException
            Console.WriteLine("This line will not be reached.");
        }
        catch (DivideByZeroException ex)
        {
            Console.WriteLine($"Caught an exception: {ex.Message}");
        }
        finally
        {
            Console.WriteLine("Finally block executed.");
        }
        Console.WriteLine("Program continues after try-catch-finally.");
    }
}
                

Example 2: Multiple catch blocks


public class MultiCatchDemo
{
    public static void Main(string[] args)
    {
        try
        {
            // Simulate different exceptions
            string text = null;
            Console.WriteLine(text.Length); // NullReferenceException
            // int[] numbers = new int[5];
            // Console.WriteLine(numbers[10]); // IndexOutOfRangeException
        }
        catch (NullReferenceException ex)
        {
            Console.WriteLine($"Caught a NullReferenceException: {ex.Message}");
        }
        catch (IndexOutOfRangeException ex)
        {
            Console.WriteLine($"Caught an IndexOutOfRangeException: {ex.Message}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Caught a general exception: {ex.Message}");
        }
    }
}
                

See Also