How to create new Exception in C#

How to create new Exception in C#

In C#, exceptions are used for handling runtime errors. While C# provides many built-in exceptions, there may be situations where you need to create your own custom exception. Here's how you can create a new exception in C#:

Step 1: Create a new class that inherits from Exception

To create a new exception, you need to create a new class that inherits from the Exception class. You can do this by using the following code:


public class MyCustomException : Exception
{
   public MyCustomException(string message) : base(message)
   {
   
   }
}

The MyCustomException class inherits from the Exception class and has a constructor that takes a message as an argument. This message is passed to the base Exception class constructor.

Step 2: Throw your custom exception

Now that you have created your custom exception, you can throw it when needed. You can do this by using the following code:


try
{
   // Some code that may throw an exception
}
catch(Exception ex)
{
   throw new MyCustomException("An error occurred while doing something.", ex);
}

The code above catches any exception that may be thrown and then throws a new instance of MyCustomException with a message and the original exception as an inner exception.

Step 3: Handle your custom exception

To handle your custom exception, you can use a try-catch block as you would with any other exception. You can also catch your custom exception specifically by using the following code:


try
{
   // Some code that may throw an exception
}
catch(MyCustomException ex)
{
   // Handle MyCustomException
}
catch(Exception ex)
{
   // Handle any other exception
}

The code above catches any MyCustomException that may be thrown and handles it specifically. Any other exception is caught by the catch block with the Exception parameter.

By creating your own custom exceptions, you can provide more specific error messages and better handle runtime errors in your C# applications.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe