Here are the steps on how to create a custom exception in C#:
Create a new class that inherits from the Exception class.
Add the Serializable attribute to the class. This will allow the class to be serialized and deserialized.
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.
Define any additional properties or methods that you need for your custom exception.
Throw an instance of your custom exception when an error occurs.
Here is an example of a custom exception class:
C#
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#
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.
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.
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)
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Here are the steps on how to create a custom exception in C#:
Exceptionclass.Serializableattribute to the class. This will allow the class to be serialized and deserialized.Exceptionclass:Exceptionobject as parameters.Here is an example of a custom exception class:
C#
This custom exception class has a property called
StudentIdthat stores the ID of the student that was not found. It also overrides theToString()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#
The
catchblock will catch any instances of theStudentNotFoundExceptionclass and handle them accordingly.Here are some reasons why you might want to create a custom exception:
Custom exceptions can be a useful way to improve the error handling in your C# code.
Custom Exception
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'
Create a class named 'CustomExceptionDemo' and call the Custom Exception 'StringNullOrEmpty' class
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.
Output