Custom exception handling in VB.NET

This article gives you a idea about exception handling in Visual Basic.Net and also how you can create your own custom exceptions.
  • 2245

In this article you will learn How to create custom exception in VB.NET.

Creating Custom Exceptions: VB.NET define your own custom exceptions to identify the occurrence of unexpected events in your code.exceptions are implemented in VB.Net as classes and objects.

  1. Create a exception kind of class and inherit it from Exception class.

  2. Override the Message property and ToString() method.

For example:

 

Module Module1

    Class NotEnoughBalanceException

        Inherits Exception

        Public Overrides ReadOnly Property Message() As String

            Get

                Return "Sorry! Not Engouh Balance"

            End Get

        End Property

    End Class

    Class Customer

        Private name As String

        Private balance As Integer

        Public Sub New(ByVal name As String, ByVal opamt As Integer)

            Me.name = name

            Me.balance = opamt

        End Sub

        Public Sub Deposit(ByVal amount As Integer)

            balance += amount

        End Sub

        Public Sub Withdraw(ByVal amount As Integer)

            If amount > balance Then

                Throw New NotEnoughBalanceException()

            End If

            balance -= amount

        End Sub

        Public Sub ShowBalance()

            Console.WriteLine("Balance of {0} is {1}", name, balance)

        End Sub

    End Class

    Class ExpTest

        Public Shared Sub Main()

            Dim c As New Customer("Amit", 5000)

            Try

                c.Deposit(4000)

                c.ShowBalance()

                c.Withdraw(20000)

                c.ShowBalance()

            Catch ex As NotEnoughBalanceException

                Console.WriteLine(ex.Message)

            End Try

 

        End Sub

    End Class

 End Module
 

 OUTPUT:

ex.gif 

Conclusion:

Hope this article would have helped you in understanding custom exception handling in VB.NET.

Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.