How to create custom Exception C# explain with valid example?
How to create custom Exception C#?
85123-Sep-2021
Updated on 06-Jul-2023
Home / DeveloperSection / Forums / How to create custom Exception C#?
How to create custom Exception C# explain with valid example?
Aryan Kumar
06-Jul-2023Here are the steps on how to create a custom exception in C#:
Exception
class.Serializable
attribute to the class. This will allow the class to be serialized and deserialized.Exception
class:Exception
object as parameters.Here is an example of a custom exception class:
C#
This custom exception class has a property called
StudentId
that 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
catch
block will catch any instances of theStudentNotFoundException
class 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.
Ravi Vishwakarma
24-Sep-2021Custom 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