MSDN Documentation

.NET Framework | C# Programming Guide

C# Error Handling

Error handling is a crucial aspect of robust software development. In C#, exception handling provides a structured way to manage runtime errors, ensuring that unexpected situations are gracefully handled rather than causing program termination.

Understanding Exceptions

An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. When an error occurs, the .NET runtime throws an exception object. This object contains information about the error, including its type and the state of the program when the error occurred.

Common exception types include:

The try-catch-finally Statement

The primary mechanism for handling exceptions in C# is the try-catch-finally statement.

Example: Basic try-catch

using System;

public class ExceptionExample
{
    public static void Main(string[] args)
    {
        try
        {
            int numerator = 10;
            int denominator = 0;
            int result = numerator / denominator; // This will throw DivideByZeroException
            Console.WriteLine($"The result is: {result}");
        }
        catch (DivideByZeroException ex)
        {
            Console.WriteLine($"Error: Cannot divide by zero.");
            Console.WriteLine($"Details: {ex.Message}");
        }
        catch (Exception ex) // Catches any other type of exception
        {
            Console.WriteLine($"An unexpected error occurred.");
            Console.WriteLine($"Details: {ex.Message}");
        }
        finally
        {
            Console.WriteLine("This block always executes.");
        }
    }
}
                

Exception Handling Strategies

When handling exceptions, consider the following strategies:

Tip: Avoid catching the generic System.Exception and doing nothing (swallowing the exception). This can hide critical errors and make debugging difficult. If you catch an exception, you should either handle it meaningfully or re-throw it.

The throw Keyword

You can explicitly throw an exception using the throw keyword. This is useful for validating input or signaling error conditions that you detect.

Example: Throwing an exception

using System;

public class InputValidator
{
    public static void ValidatePositiveNumber(int number)
    {
        if (number < 0)
        {
            throw new ArgumentOutOfRangeException(nameof(number), "The number must be positive.");
        }
        Console.WriteLine($"Valid number: {number}");
    }

    public static void Main(string[] args)
    {
        try
        {
            ValidatePositiveNumber(-5);
        }
        catch (ArgumentOutOfRangeException ex)
        {
            Console.WriteLine($"Input validation failed: {ex.Message}");
        }
    }
}
                

Best Practices