Creating Your Own Exception Classes in VB.NET
In this article I will explain you about Creating Your Own Exception Classes in VB.NET
To create your own exception class, the .NET framework requires you to derive your class from the System.Exception class and recommends that you implement all the constructors that are implemented by the base class. Here are some important recommendations:
Give a meaningful name to your Exception class and end it with Exception.
Do not develop a new Exception class unless there is a scenario for developers needing the class.
Throw the most specific exception possible.
Give meaningful messages.
Do use InnerExceptions.
When wrong arguments are passed, throw an ArgumentException or a subclass of it (e.g., ArgumentNullException), if necessary.
Let's go ahead and create an exception called MyException. The code and test for the exception are shown in Example below.
Public Class MyException
'Constructors. It is recommended that at least all the
'base class Exception are implemented
Public Sub New()
Public Sub New(ByVal message As String)
Public Sub New(ByVal message As String, ByVal e As Exception)
'If there is extra error information that needs to be captured
'create properties for them.
Private strExtraInfo As String
Public Property ExtraErrorInfo() As String
Set(ByVal value As String)
strExtraInfo = value
Dim m As MyException
m = New MyException("My Exception Occured")
m.ExtraErrorInfo = "My Extra Error Information"
Catch e As MyException
In above example we create the MyException class, which is derived from the System.Exception class. As the code shows, all constructors simply call the base class constructors the typical way to implement constructors. We also create a property called ExtraErrorInfo, which can be used to store any other extra error information. The reason you would create your own exception type is so the program catching this exception can take a specific action. You could also add your own properties to give any extra error information.
Hope this article would have helped you in understanding Creating Your Own Exception Classes in