---
title: "How to create custom Exception C#?"  
description: "How to create custom Exception C#?"  
author: "Ethan Karla"  
published: 2021-09-23  
updated: 2023-07-06  
canonical: https://www.mindstick.com/forum/156754/how-to-create-custom-exception-c-sharp  
category: "exception handling"  
tags: ["c#"]  
reading_time: 4 minutes  

---

# How to create custom Exception C#?

How to create [custom Exception](https://www.mindstick.com/forum/159237/how-to-create-a-custom-exception-in-java-and-when-would-to-use-it) C# [explain](https://www.mindstick.com/forum/157854/what-is-system-debugging-explain-some-system-debugging-tools-used-in-modern-computer-systems) with valid example?

## Replies

### Reply by Aryan Kumar

Here are the steps on how to create a custom exception in C#:

1. Create a new class that inherits from the `Exception` class.
2. Add the `Serializable` attribute to the class. This will allow the class to be serialized and deserialized.
3. Implement the three common constructors of the `Exception` class:

   - The default constructor.
   - A constructor that takes a string message as a parameter.
   - A constructor that takes a string message and an `Exception` object as parameters.

4. Define any additional properties or methods that you need for your custom exception.
5. Throw an instance of your custom exception when an error occurs.

Here is an example of a custom exception class:

C#

```plaintext
public class StudentNotFoundException : Exception, ISerializable {

    public StudentNotFoundException() { }

    public StudentNotFoundException(string message) : base(message) { }

    public StudentNotFoundException(string message, Exception inner) : base(message, inner) { }

    public int StudentId { get; set; }

    public override string ToString() {
        return $"Student with ID {StudentId} not found.";
    }

}
```

This custom exception class has a property called `StudentId` that stores the ID of the student that was not found. It also overrides the `ToString()` method to return a more meaningful message when the exception is thrown.

To throw an instance of this custom exception, you would use the following code:

C#

```plaintext
try {
    // Do something that might throw an exception.
} catch (StudentNotFoundException e) {
    // Handle the exception.
}
```

The `catch` block will catch any instances of the `StudentNotFoundException` class and handle them accordingly.

Here are some reasons why you might want to create a custom exception:

- To add more information to the exception message.
- To distinguish between different types of errors.
- To provide a more user-friendly error message.

Custom exceptions can be a useful way to improve the error handling in your C# code.

### Reply by Ravi Vishwakarma

**[Custom](https://www.mindstick.com/blog/12298/use-custom-writing-services-to-get-through-the-finals) [Exception](https://www.mindstick.com/articles/1824/objective-c-exception-handling)**

If we want, we can also create our own Exception Class, which can work to solve a certain problem of an application. To create our own Sub Exception Class, we have to derive our Sub Class from C# Built-In Exception Class. We do not have to implement anything in our class, rather Exception Class is already available in C#, which already has facilities to handle different types of Exceptions. The Exception class does not have any methods of its own, rather all the methods of the Throwable class are available in it. Therefore, in our Sub Class also all the Methods of Throwable Class are available and those Methods are also available, which we create as per our requirement.

## Example

We Define the custom exception named **'StringNullOrEmpty'**

```
using System;sealed class StringNullOrEmpty : Exception{ public StringNullOrEmpty() : base() { } public StringNullOrEmpty(string ExceptionMesage) : base(ExceptionMesage) { }}
```

Create a class named **'CustomExceptionDemo'** and call the Custom Exception **'StringNullOrEmpty'** class

```
class CustomExceptionDemo{ private string msg; public CustomExceptionDemo() {this.msg=string.Empty;} public CustomExceptionDemo(string message) {  if(string.IsNullOrEmpty(message))     throw new StringNullOrEmpty('Message is empty or null');  else   this.msg=message; }
 public void GetMessage(){  Console.WriteLine('Message is : '+this.msg); }}
```

First of all, send data in CustomExceptionDemo class str= 'hello' then an exception is not occur but we send the null value then occur exception.

```
class MyProgram{  static void Main(string[ ] args)    {       try      {      string str='Hello';      CustomExceptionDemo ced=new CustomExceptionDemo(str); // no exception occur      ced.GetMessage();      str=null;      ced=new CustomExceptionDemo(str); // Exception Occur      ced.GetMessage();      }catch(Exception ex)      {       Console.WriteLine('Error message : ' + ex.Message + '\n\n' + ex);      }    } }
```

## Output

```
Message is : Hello
Error message : Message is empty or null
StringNullOrEmpty: Message is empty or null
   at CustomExceptionDemo..ctor(String message)
   at MyProgram.Main(String[] args)
```


---

Original Source: https://www.mindstick.com/forum/156754/how-to-create-custom-exception-c-sharp

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
