ARTICLE
Creating Your Own Exception Classes in VB.NET
In this article I will explain you about Creating Your Own Exception Classes in VB.NET
Download
Files:
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.
Example Code
Module Module1
Public Class MyException
Inherits Exception
'Constructors. It is recommended that at least all the
'constructors
of
'base class
Exception are implemented
Public Sub New()
MyBase.New()
End Sub
Public Sub New(ByVal
message As String)
MyBase.New(message)
End Sub
Public Sub New(ByVal
message As String,
ByVal
e As Exception)
MyBase.New(message, e)
End Sub
'If there is extra error information that needs to be captured
'create properties for them.
Private strExtraInfo As String
Public Property
ExtraErrorInfo() As String
Get
Return strExtraInfo
End Get
Set(ByVal
value As String)
strExtraInfo = value
End Set
End Property
End Class
Sub
Main()
Try
Dim m As MyException
m = New MyException("My
Exception Occured")
m.ExtraErrorInfo = "My
Extra Error Information"
Throw m
Catch e As MyException
Console.WriteLine([String].Concat(e.StackTrace,
e.Message))
Console.WriteLine(e.ExtraErrorInfo)
End Try
Console.ReadLine()
End Sub
End Module
Output

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.
Conclusion
Hope this article would have helped you in
understanding Creating Your Own Exception Classes in