Exception Handling

C# Exception Handling

Exception handling in C# is a mechanism to handle runtime errors, ensuring the program can respond to unexpected conditions gracefully. The primary way to handle exceptions is through the use of try, catch, finally, and throw statements.

Key Concepts

  1. try-catch Block

Surround code that might throw an exception with a try block, and handle exceptions with one or more catch blocks.

Examples

Basic try-catch Example

using System;

class Program
{
    static void Main()
    {
        try
        {
            int[] numbers = { 1, 2, 3 };
            Console.WriteLine(numbers[5]); // This will throw an exception
        }
        catch (IndexOutOfRangeException ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
        }
    }
}

Advanced Features

  1. finally Block

The finally block contains code that is always executed, regardless of whether an exception is thrown or caught. It is typically used for cleanup code.

  1. throw Statement

Use the throw statement to explicitly throw an exception, either caught or newly created.

  1. Custom Exceptions

Define your own exceptions by creating a class that inherits from Exception.

Summary

  • try-catch: Handle exceptions where they occur.

  • finally: Execute code regardless of exceptions, useful for cleanup.

  • throw: Explicitly throw exceptions.

  • Custom Exceptions: Create exceptions specific to application needs.

C# exception handling provides robust mechanisms to manage errors and maintain program stability, making it easier to develop reliable applications.