Creating Custom Exceptions
In C#, exception handling is a fundamental aspect of writing robust and error-free code. One of the features of C# is the ability to create custom exceptions. This tutorial aims to help you understand how to create and use custom exceptions in your C# programs.
What is a Custom Exception?
A custom exception is a user-defined exception that you can create to handle specific situations in your program. These exceptions are created by deriving a class from the Exception
class provided by the .NET Framework.
Why Use Custom Exceptions?
Creating custom exceptions can make your code more readable and maintainable. They allow you to handle specific errors that are unique to your application, and provide meaningful error messages to the user.
How to Create a Custom Exception
Creating a custom exception in C# is simple. Follow the steps below:
Define a New Exception Class
Declare a new class that derives from the
Exception
class. For instance, if we want to create a custom exception calledInvalidAgeException
, we would declare it as follows:public class InvalidAgeException : Exception
{
}Add a Constructor to the Class
Add a constructor to the new class that takes a string message as a parameter. This message will be displayed when the exception is thrown. Here is how you can do it:
public class InvalidAgeException : Exception
{
public InvalidAgeException(string message) : base(message)
{
}
}The
base(message)
call is used to pass the error message to the baseException
class.Override the
ToString
Method (Optional)You can override the
ToString
method in your custom exception class to provide a custom string representation of your exception. This step is optional.public override string ToString()
{
return $"InvalidAgeException: {Message}";
}
How to Throw a Custom Exception
To throw a custom exception, you use the throw
keyword followed by an instance of your exception class. Here is an example:
if (age < 0)
{
throw new InvalidAgeException("Age cannot be negative.");
}
In the code snippet above, when the age
is less than 0, an InvalidAgeException
is thrown with the message "Age cannot be negative."
How to Catch a Custom Exception
Catching a custom exception is the same as catching a standard exception. You use a try/catch
block. Here is an example:
try
{
// Code that may throw an exception
}
catch (InvalidAgeException ex)
{
Console.WriteLine(ex.Message);
}
In the code snippet above, if an InvalidAgeException
is thrown within the try
block, it will be caught in the catch
block, and the exception message will be written to the console.
And that's it! You've created your first custom exception in C#. By creating your own exceptions, you can handle errors more efficiently and make your code easier to read and maintain. Happy coding!