Exception Handling in VB.net – Try, Catch, Finally, and Throw

VB.NET Exception Handling

Exceptions in VB.net provide a way to transfer control from one part of a program to another.

VB.net Exception Handling is built upon four keywords – Try, Catch, Finally, and Throw.

Try Exception

A Try Exception in VB.net is used to keep track of a specific exception that the program might throw.

And it always comes after one or more catch blocks to deal with these exceptions.

Catch Exception in VB.net

Catch Exception in VB.net is a section of code that, when a problem occurs in a program, handles the exception with an exception handler.

Finally Exception

Finally, Exception in VB.net is used to execute a set of statements in a program, whether an exception has occurred.

Throw Exception

A Throw Exception in VB.net is used to throw an exception following the occurrence of a problem, as the name suggests.

What is Exception in VB.net?

An Exception in VB.net is an unwanted error that occurs during the execution of a program and can be a system exception or application exception.

Exceptions are nothing but some abnormal and typically an event or condition that arises during the execution, which may interrupt the normal flow of the program.

Syntax of Exception Handling in VB.net

A method catches an exception by combining the Try and Catch keywords, presuming a block will generate an exception.

The code that might cause an exception is enclosed in a Try/Catch block.

Protected code is code that is contained within a Try/Catch block.

Here’s the Syntax for using Try/Catch looks like the following:

Try
[ tryStatements ]
[ Exit Try ]
[ Catch [ exception [ As type ] ] [ When expression ]
[ catchStatements ]
[ Exit Try ] ]
[ Catch ... ]
[ Finally
[ finallyStatements ] ]
End Try

If your try block raises more than one exception in different circumstances, you can list down multiple catch statements to catch the various exception types.

Exception Classes in VB.net

In the .Net Framework, exceptions are represented by classes.

The exception classes in .Net Framework are mainly directly or indirectly derived from the System.Exception class.

Some of the exception classes are derived from the System.Exception class is the System.ApplicationException and System.SystemException classes.

The System.ApplicationException class supports exceptions generated by application programs.

So the exceptions defined by the programmers should derive from this class.

The System.SystemException class is the base class for all predefined system exceptions.

The following table provides some of the predefined exception classes derived from the Sytem.SystemException class.

Exception Class in VB.netDescription
System.IO.IOExceptionHandles I/O errors.
System.IndexOutOfRangeExceptionHandles errors generated when a method refers to an array index out of range.
System.ArrayTypeMismatchExceptionHandles errors generated when type is mismatched with the array type.
System.NullReferenceExceptionHandles errors generated from deferencing a null object.
System.DivideByZeroExceptionHandles errors generated from dividing a dividend with zero.
System.InvalidCastExceptionHandles errors generated during typecasting.
System.OutOfMemoryExceptionHandles errors generated from insufficient free memory.
System.StackOverflowExceptionHandles errors generated from stack overflow.
Exception Class in VB.net

Handling Exceptions in VB.net

Try and catch blocks, a structured approach to the exception handling issues, are provided by VB.net.

The main program statements and the error-handling statements are divided using these blocks.

These error-handling blocks are implemented using the Try, Catch, and Finally keywords.

Following is an example of throwing an exception when dividing by zero condition occurs:

Module exceptionProg
   Sub division(ByVal num1 As Integer, ByVal num2 As Integer)
      Dim result As Integer
      Try
         result = num1 \ num2
      Catch e As DivideByZeroException
         Console.WriteLine("Exception caught: {0}", e)
      Finally
         Console.WriteLine("Result: {0}", result)
      End Try
   End Sub
   Sub Main()
      division(25, 0)
      Console.ReadKey()
  End Sub
End Module

When the above code is compiled and executed, it produces the following result:

Exception caught: System.DivideByZeroException: Attempted to divide by zero.

You can test the above example here! ➡ VB.net Online Compiler

Creating User-Defined Exceptions in VB.net

You can create your own exceptions as well. ApplicationException is a base class from which user-defined exception classes are derived.

Example program in Creating User-Defined Exceptions in VB.net:

Module exceptionProg
   Public Class TempIsZeroException : Inherits ApplicationException
      Public Sub New(ByVal message As String)
         MyBase.New(message)
      End Sub
   End Class
   Public Class Temperature
      Dim temperature As Integer = 0
      Sub showTemp()
         If (temperature = 0) Then
            Throw (New TempIsZeroException("Zero Temperature found"))
         Else
            Console.WriteLine("Temperature: {0}", temperature)
         End If
      End Sub
   End Class
   Sub Main()
      Dim temp As Temperature = New Temperature()
      Try
         temp.showTemp()
      Catch e As TempIsZeroException
         Console.WriteLine("TempIsZeroException: {0}", e.Message)
      End Try
      Console.ReadKey()
   End Sub
End Module

When the above code is compiled and executed, it produces the following result:

TempIsZeroException: Zero Temperature found

You can test the above example here! ➡ VB.net Online Compiler

Throwing Objects in VB.net

You can throw an object if it is either directly or indirectly derived from the System.Exception class.

You can use a throw statement in the catch block to throw the present object as:

Throw [ expression ]

Example Program of Throwing Objects in VB.net:

Module exceptionProg
   Sub Main()
      Try
         Throw New ApplicationException("A custom exception _ is being thrown here...")
      Catch e As Exception
         Console.WriteLine(e.Message)
      Finally
         Console.WriteLine("Now inside the Finally Block")
      End Try
      Console.ReadKey()
   End Sub
End Module

When the above code is compiled and executed, it produces the following result:

A custom exception _ is being thrown here…
Now inside the Finally Block

You can test the above example here! ➡ VB.net Online Compiler

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.


Leave a Comment