Creating Custom Exceptions in C#: Enhancing Error Handling and Code Clarity
Learn how to define and use custom exception types in C# for improved error handling and more informative error messages. This tutorial demonstrates creating custom exception classes that inherit from `System.Exception`, explaining how to throw and catch custom exceptions for building more robust and maintainable applications.
Creating Custom Exceptions in C#
C# allows you to define your own custom exception types. This is very helpful for creating more informative and meaningful error messages in your applications, improving both error handling and code clarity.
Defining Custom Exceptions
To create a custom exception, you create a new class that inherits from the `System.Exception` class. This new class represents a specific type of exception relevant to your application's logic.
Example: `InvalidAgeException`
public class InvalidAgeException : Exception {
public InvalidAgeException(string message) : base(message) { }
}
This code defines a custom exception called `InvalidAgeException`. It inherits from `Exception` and takes a message string in its constructor.
Using Custom Exceptions
You throw a custom exception using the `throw` keyword:
if (age < 18) {
throw new InvalidAgeException("Age must be 18 or older.");
}
You handle custom exceptions using `try-catch` blocks, just like with built-in exceptions. This enables you to implement specific error handling tailored to your application's needs.
Example: Age Validation
// ... (InvalidAgeException class definition) ...
public class AgeValidator {
public static void Main(string[] args) {
try {
ValidateAge(15);
} catch (InvalidAgeException ex) {
Console.WriteLine(ex.Message);
}
}
static void ValidateAge(int age) {
if (age < 18) throw new InvalidAgeException("Too young!");
}
}