Start Coding

Topics

C# Custom Exceptions

Custom exceptions in C# allow developers to create specialized error types tailored to their application's needs. By extending the built-in Exception class, you can define your own exception classes with additional properties and behaviors.

Why Use Custom Exceptions?

Custom exceptions offer several benefits:

  • Improved error handling and reporting
  • Enhanced code readability and maintainability
  • Better separation of concerns
  • More precise exception catching and handling

Creating a Custom Exception

To create a custom exception, follow these steps:

  1. Define a new class that inherits from Exception or a more specific exception type
  2. Implement constructors to handle different scenarios
  3. Add any custom properties or methods as needed

Example: Custom Exception Class


public class InvalidUserAgeException : Exception
{
    public int Age { get; }

    public InvalidUserAgeException(int age)
        : base($"Invalid age: {age}. Age must be between 18 and 120.")
    {
        Age = age;
    }

    public InvalidUserAgeException(string message, int age)
        : base(message)
    {
        Age = age;
    }

    public InvalidUserAgeException(string message, Exception inner, int age)
        : base(message, inner)
    {
        Age = age;
    }
}
    

Using Custom Exceptions

Once you've defined a custom exception, you can throw it like any other exception using the throw keyword. Here's an example:


public void RegisterUser(string name, int age)
{
    if (age < 18 || age > 120)
    {
        throw new InvalidUserAgeException(age);
    }

    // Proceed with user registration
}
    

Catching Custom Exceptions

To catch a custom exception, use a try-catch block as you would with built-in exceptions:


try
{
    RegisterUser("John Doe", 150);
}
catch (InvalidUserAgeException ex)
{
    Console.WriteLine($"Error: {ex.Message}");
    Console.WriteLine($"Attempted age: {ex.Age}");
}
catch (Exception ex)
{
    Console.WriteLine($"An unexpected error occurred: {ex.Message}");
}
    

Best Practices

  • Name your custom exceptions with an "Exception" suffix
  • Inherit from the most appropriate exception base class
  • Implement standard constructors for consistency
  • Include relevant information in custom properties
  • Use custom exceptions judiciously to avoid overcomplicating error handling

Conclusion

Custom exceptions in C# provide a powerful way to handle application-specific errors. By creating tailored exception classes, you can improve error reporting, enhance code readability, and make your application more robust. Remember to use custom exceptions thoughtfully and in conjunction with built-in exception types for optimal error handling.

For more advanced exception handling techniques, consider exploring C# Exception Filters and Multiple Catch Blocks.