C# - User defined/custom exceptions?
In C#, you can create custom exceptions, also known as user-defined exceptions, to handle specific error scenarios in your code. These custom exceptions extend the built-in Exception
class and allow you to provide more context and information about the error. Creating custom exceptions helps make your code more organized and understandable.
Developers can make their own special types of errors, called custom exceptions. These custom exceptions are like unique error messages that can include extra details about what went wrong. This helps other developers figure out and deal with the problem better.
To create a custom exception, you usually create a new class based on the basic 'System.Exception' class or something related, like 'System.ApplicationException'. It's a good idea to add "Exception" to the end of the custom exception's name to show that it's for handling specific types of errors.
using System;
// Define a custom exception by inheriting from Exception class
public class CustomException : Exception
{
public CustomException(string message) : base(message)
{
}
}
class Program
{
static void Main()
{
try
{
// Simulate a situation where your custom exception might occur
int age = -5;
if (age < 0)
{
// Throw your custom exception with a specific error message
throw new CustomException("Age cannot be negative.");
}
Console.WriteLine("Age: " + age);
}
catch (CustomException ex)
{
Console.WriteLine("Custom Exception Caught: " + ex.Message);
}
catch (Exception ex)
{
Console.WriteLine("General Exception Caught: " + ex.Message);
}
}
}
Output:
Custom Exception Caught: Age cannot be negative.
In this example:
-
We define a custom exception called
CustomException
that inherits from the built-in Exception class. The constructor of CustomException
takes a custom error message as an argument.
-
Inside the
Main
method, we simulate a scenario where the custom exception might occur by setting the age
variable to a negative value.
-
We use a
try-catch
block to handle exceptions. If the age
is negative, we throw the CustomException
with a specific error message.
-
In the catch block, we catch the
CustomException
and display the custom error message. If any other general exception occurs, it will be caught by the second catch block.
By creating and using custom exceptions, you can provide meaningful error messages and improve the readability and maintainability of your code when handling exceptional cases specific to your application.