In the world of programming, handling errors gracefully is crucial for building robust applications. C# provides a powerful mechanism to handle exceptions through its exception handling model. While .NET offers a wide range of built-in exceptions, sometimes you need to define your own custom exceptions to better suit the specific needs of your application.
Custom exceptions allow you to create more meaningful error messages and handle errors in a way that is specific to your application's context. In this tutorial, we will explore how to create and use custom exceptions in C#.
An exception in C# is an object that describes an error or unusual condition that has occurred during the execution of a program. When an error occurs, an exception is thrown, and if not handled properly, it can terminate your application. Custom exceptions are user-defined classes that inherit from the base Exception class.
To create a custom exception, you need to define a new class that inherits from Exception. You can also override properties like Message or add additional properties to provide more context about the error.
Let's walk through creating and using a custom exception in C# with some practical examples.
First, we need to define a new class that inherits from Exception. Let's create a custom exception called InvalidAgeException which will be used to handle errors related to invalid age inputs.
1public class InvalidAgeException : Exception2{3public int Age { get; }45public InvalidAgeException(int age, string message) : base(message)6{7Age = age;8}9}
In this example, we have added an additional property Age to store the invalid age value. The constructor takes both the age and a custom error message.
Now that we have our custom exception defined, let's see how to use it in a method that validates user input for age.
1public class AgeValidator2{3public void ValidateAge(int age)4{5if (age < 0 || age > 120)6{7throw new InvalidAgeException(age, "Age must be between 0 and 120.");8}9}10}
In the ValidateAge method, we check if the provided age is within a valid range (0 to 120). If not, we throw an InvalidAgeException.
To handle the custom exception, you can use a try-catch block. Let's see how this works in practice.
1public class Program2{3public static void Main()4{5AgeValidator validator = new AgeValidator();67try8{9Console.Write("Enter your age: ");10int age = int.Parse(Console.ReadLine());11validator.ValidateAge(age);12Console.WriteLine("Age is valid.");13}14catch (InvalidAgeException ex)15{16Console.WriteLine($"Error: {ex.Message}");17Console.WriteLine($"Invalid Age: {ex.Age}");18}19}20}
In this example, we prompt the user to enter their age and then call ValidateAge. If an InvalidAgeException is thrown, it is caught in the catch block where we print the error message and the invalid age.
Let's see what happens when you run this program:
$ dotnet runEnter your age: 150Error: Age must be between 0 and 120.Invalid Age: 150
Enter your age: 150 Error: Age must be between 0 and 120. Invalid Age: 150
As you can see, the custom exception provides a clear and specific error message along with the invalid age value.
Now that you have learned how to create and use custom exceptions in C#, you might want to explore other aspects of error handling such as file I/O operations. Understanding how to handle files safely is essential for many applications, so make sure to check out our next tutorial on "File I/O Operations in C#".
By mastering custom exceptions and other error handling techniques, you will be well-equipped to build more resilient and user-friendly applications.
Info
Remember, custom exceptions should be used judiciously. Only define them when they provide meaningful information that enhances the error handling process.