Skip to content
the poor coder

How to create new Exception in C#

Poor Man
Published
Reading time
1 min read
On this page

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:

Text

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:

Text

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:

Text

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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC