Skip to content

Exception Handling

Exception handling provides a structured way to detect and handle runtime errors in your applications. It helps maintain program stability and provides meaningful error information.

Try-Catch Block

The try-catch block allows you to handle exceptions gracefully, preventing application crashes and providing appropriate error handling.

csharp
try
{
    // Code that might throw an exception
    int result = 10 / 0;
}
catch (DivideByZeroException ex)
{
    // Handle specific exception
    Console.WriteLine($"Division error: {ex.Message}");
}
catch (Exception ex)
{
    // Handle any other exception
    Console.WriteLine($"Error: {ex.Message}");
}
finally
{
    // Code that always executes
    Console.WriteLine("Cleanup code");
}

Custom Exceptions

Custom exceptions allow you to create application-specific error types, making error handling more meaningful and specific to your domain.

csharp
public class CustomException : Exception
{
    public CustomException() : base() { }
    public CustomException(string message) : base(message) { }
    public CustomException(string message, Exception inner) 
        : base(message, inner) { }
}

Throwing Exceptions

Throwing exceptions allows you to indicate error conditions in your code and handle them appropriately at a higher level.

csharp
if (age < 0)
{
    throw new ArgumentException("Age cannot be negative");
}