What is an Exception?

An exception refers to a problem that arises during program execution. It is brought about by an unexpected circumstance. A good example is when you are performing a division operation, and then you divide by zero (0). An exception will be raised.

In this Visual Basic Tutorial, you will learn:

What is Exception Handling?

With exceptions, you can transfer the control of a program from one part to another. In VB.NET, exceptions are handled using the following 4 keywords:

Keyword Detail
Try The work of the Try block is to identify the code block for which a specific exception will be activated. It should be followed by a catch block(s).
Catch Catching of the Exception is done in this block. It is an exception handler in which the Exception is handled.
Finally Use the Finally block to run a set of statements whether an exception has occurred or not.
Throw An exception is thrown after the occurrence of a problem. This is the work of the Throw keyword.

Syntax of Try/Catch

The Try/Catch statements take the syntax given below:

Try
   [ try_Statement(s) ]
   [ Exit Try ]
[ Catch [ exception_name [ As type ] ] [ When expression ]
   [ catch_Statement(s) ]
   [ Exit Try ] ]
[ Catch - ]
[ Finally
   [ finally_Statement(s) ] ]
End Try

The Try/Catch block should surround the code that may raise an exception. This code is known as a protected code. You can use multiple catch statements when you need to catch various types of exceptions.

Example to Handle Exceptions

With the Try/Catch statements, you can separate your ordinary program code from the error-handling System. Let us demonstrate how to handle an exception using the Try, Catch, and Finally keywords.

Step 1) Create a new console application.

Step 2) Use this code:

Module Module1
    Sub divisionFunction(ByVal n1 As Integer, ByVal n2 As Integer)
        Dim answer As Integer
        Try
            answer = n1 \ n2
        Catch ex As DivideByZeroException
            Console.WriteLine("Exception: {0}", ex)
        Finally
            Console.WriteLine("Answer is: {0}", answer)
        End Try
    End Sub
    Sub Main()
        divisionFunction(4, 0)
        Console.ReadKey()
    End Sub

End Module

Step 3) Click the Start button from the toolbar to execute the code. You should get the following output:

Here is a screenshot of the code:

Explanation of Code:

  1. Creating a module named Module1.
  2. Creating a sub-procedure named divisionFunction with two integer arguments n1 and n2. The ByVal is a VB.NET keyword stating that the values of the arguments will be passed by value.
  3. Creating an integer variable named answer.
  4. Start of the Try/Catch block. We need to surround the code that we suspect may raise an exception with this block.
  5. Performing a division operation between the values of variables n1 and n2. The result of the division operation is assigned to the variable answer. This code may raise an exception, for example, when we divide a number by zero, hence we have surrounded it with the Try/Catch blocks.
  6. Catching the Exception named DivideByZeroException and assigning the generated exception message to the ex.
  7. Printing some text on the console to notify the user of the type/name of the Exception that was raised.
  8. The Finally block. This will execute whether an exception is caught or not.
  9. Printing some text on the console showing the result of the division operation.
  10. End of the Try block, that is, end of the error-handling code.
  11. End of the divisionFunction sub-procedure.
  12. Start of the main sub-procedure.
  13. Calling/invoking the divisionFunction sub-procedure. The values of the two integer arguments are passed here. The value of n1=4 and n2=0. This means the division operation will be 4\0, that is, n1\n2.
  14. Pausing the console window waiting for the user to take action to close it.
  15. End of the main sub-procedure.
  16. End of the module.

User-Defined Exceptions

VB.NET allows you to define your own exceptions. You can get user-defined exception classes from ApplicationException class. Let us demonstrate this by an example:

Step 1) Create a new console application.

Step 2) Use the following code:

Module Module1

    Public Class HeightIsZeroException : Inherits ApplicationException
        Public Sub New(ByVal text As String)
            MyBase.New(text)
        End Sub
    End Class
    Public Class Height
        Dim height As Integer = 0
        Sub showHeight()
            If (height = 0) Then
                Throw (New HeightIsZeroException("Zero Height found"))
            Else
                Console.WriteLine("Height is: {0}", height)
            End If
        End Sub
    End Class
    Sub Main()
        Dim hght As Height = New Height()
        Try
            hght.showHeight()
        Catch ex As HeightIsZeroException
            Console.WriteLine("HeightIsZeroException: {0}", ex.Message)
        End Try
        Console.ReadKey()
    End Sub

End Module

Step 3) Click the Start button from the top bar to execute the code. You should get the following output:

Here is a screenshot of the code:

Explanation of Code:

  1. Creating a module named Module1.
  2. Creating an exception class named HeightIsZeroException. The class inherits all the ApplicationException class.
  3. Creating a sub-procedure named New. It will take one string argument named text.
  4. Calling the base class constructor and passing to it the above argument.
  5. End of the New sub-procedure.
  6. End of the HeightIsZeroException class.
  7. Creating a class named Height. Its public access modifier is Public, meaning that it will be publicly accessible.
  8. Creating an integer variable named Height and initializing its value to 0.
  9. Creating a sub-procedure named showHeight().
  10. Checking for when the value of the variable Height is 0. We have used the If…Then condition.
  11. To Throw the HeightIsZeroException if the above condition is true. The message Zero Height Found will be shown when this Exception is thrown.
  12. The Else part to be executed when the If condition is not true.
  13. Message to print on the console showing the Height when it is not 0.
  14. End of the If condition.
  15. End of the showHeight() subprocedure.
  16. End of the class Height.
  17. Start of the main sub-procedure.
  18. Creating an object named Height as an instance of the Height class.
  19. Start of the exception handling block.
  20. Invoking the showHeight() sub-procedure defined in the Height class. We have used an object of this class to access this method. This line may result into an exception. Therefore, we have surrounded it with an exception handling code.
  21. Catching the HeightIsZeroException Exception as object ex in case it occurs.
  22. The message to print on the console when the HeightIsZeroException is caught.
  23. End of the exception handling block.
  24. Pause the console window waiting for a user to take action to close it.
  25. End of the main sub-procedure.
  26. End of the module.

Throwing Objects

In exception handling, you can choose to throw an object. However, the object must be derived from System. Exceptionclass, directly or indirectly. For example:

Step 1) Create a new console application.

Step 2) Use the following code:

Module Module1

    Sub Main()
        Try
            Throw New ApplicationException("Throwing a custom exception")
        Catch ex As Exception
            Console.WriteLine(ex.Message)
        Finally
            Console.WriteLine("The Finally Block")
        End Try
        Console.ReadKey()
    End Sub


End Module

Step 3) Click the Start button from the top bar to execute the code. You should get the following:

Here is a screenshot of the code:

Explanation of Code:

  1. Creating a module named Module1.
  2. Start of the main sub-procedure.
  3. Start of the error handling code.
  4. Throwing an exception object. This code may generate an exception hence we have surrounded it with a Try/Catch block.
  5. Catching an exception as object ex if the line throws an exception.
  6. Printing the exception message on the console in case it occurs.
  7. The Finally block to run whether an exception is caught or not.
  8. The message to print on the console when the Finally block is executed.
  9. End of the exception handling code.
  10. Pause the console for a while waiting for a user to take action to close it.
  11. End of the main sub-procedure.
  12. End of the module.

Summary

  • An exception refers to a problem that arises during program execution brought about by an unexpected circumstance.
  • If you suspect that some code will generate an exception, surround it with a Try/Catch block.
  • The Finally block comes after the Try/Catch block and executes whether an exception is caught or not.
  • VB.NET allows us to create custom exceptions.

 

YOU MIGHT LIKE: