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.
Custom exceptions offer several benefits:
To create a custom exception, follow these steps:
Exception
or a more specific exception type
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;
}
}
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
}
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}");
}
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.