Custom exception objects in .Net:
Why to make custom exception class?
There are various Exception objects available in .net but what if there's no applicable Exception object to the problem of our code, the solution is to create an Exception class of our own.
Making a custom exception class:
For a basic Exception class, it has to include just three things.First, the class must be inherited from the System.Exception object.(We can derive the custom exception directly from the System.Exception class or can use an intermediate exception like SystemException or ApplicationException as base class.)Second, we need to provide three constructors (one that accepts a message and an exception object, one that accepts a message, and one that accepts no parameters at all).These three constructors correspond to three constructors that are part of the base Exception object so, thirdly within each constructor, we just need to use MyBase.New to pass the values accepted by our constructor to the corresponding base constructor.
For example:
Public Class OptionsException:Exception
{
Public New()
{
MyBase.New("Invalid options selected");
}
Public New(string message)
{
MyBase.New(message);
}
Public New(string message, Exception Exception )
{
MyBase.New(message, Exception);
}
}
Custom Exception Class with Additional Properties:
Suppose we want to add property to hold information related to the exception & the property should be read only which is the basic pattern for Exception.
For this we will take a variable and wrap it in a ReadOnly property so that the variable's value can be read.
Then we can take two constructors, the first constructor accepts an option, a message and an InnerException object and the other constructor accepts an option and a message. In both constructors, after calling the corresponding base constructor, we can set the ReadOnly variable with the option passed to the constructor.
For Example:
[Serializable]
Public Class OptionsException:Exception
{
Private string _option;
Public string OptionSelected
get
{
Return _option;
}
Public New(string Message,string BadOption)
{
MyBase.New(Message);
_option = BadOption;
}
Public New(string Message,string BadOption,Exception Exception)
{
MyBase.New(Message, Exception);
_option = BadOption;
}
}
0 Comment(s)