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 TryIf 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.net | Description |
|---|---|
| System.IO.IOException | Handles I/O errors. |
| System.IndexOutOfRangeException | Handles errors generated when a method refers to an array index out of range. |
| System.ArrayTypeMismatchException | Handles errors generated when type is mismatched with the array type. |
| System.NullReferenceException | Handles errors generated from deferencing a null object. |
| System.DivideByZeroException | Handles errors generated from dividing a dividend with zero. |
| System.InvalidCastException | Handles errors generated during typecasting. |
| System.OutOfMemoryException | Handles errors generated from insufficient free memory. |
| System.StackOverflowException | Handles errors generated from stack overflow. |
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 ModuleWhen 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 ModuleWhen 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 ModuleWhen 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.
PREVIOUS
NEXT
Common use cases for Exception Handling
Exception Handling shows up frequently in production VB.NET codebases. The most common patterns:
- Business logic layer. Encapsulate rules and workflows separate from the UI.
- Data access patterns. Bridge between UI events and database operations cleanly.
- Utility helpers. Reusable methods for string processing, date arithmetic, or format conversion.
- Integration with .NET libraries. Interoperate with System.IO, System.Net, System.Text.RegularExpressions, and more.
- Legacy migration. Modernize VB6 code by wrapping old logic in idiomatic VB.NET constructs.
Working code example
Public Module Program
Public Sub Main(args As String())
' Practical demonstration of Exception Handling
Dim result As String = ProcessData("sample input")
Console.WriteLine("Result: " & result)
Console.ReadKey()
End Sub
Private Function ProcessData(input As String) As String
If String.IsNullOrWhiteSpace(input) Then
Return "empty"
End If
Return input.ToUpper()
End Function
End Module
Best practices when working with Exception Handling
- Explicit typing. Enable Option Strict On at the project level to force compile-time type checking.
- Namespace hygiene. Group related types under project-specific namespaces to avoid conflicts with .NET Framework types.
- Consistent naming. Follow Microsoft’s VB.NET style guide: PascalCase for public members, camelCase for locals.
- Error handling with Try/Catch. Prefer specific exception types over catch-all Exception blocks.
- Modern language features. Use string interpolation, LINQ, and Async/Await where they clarify intent.
Common pitfalls
- Late binding. Without Option Strict, VB.NET falls back to late-binding, hiding bugs until runtime.
- Nothing vs empty string. String.IsNullOrEmpty and String.IsNullOrWhiteSpace catch both cases; avoid checking IsNothing alone.
- Integer overflow. Use Long or Decimal for arithmetic that may exceed Int32.MaxValue.
- Date parsing across cultures. Always pass CultureInfo.InvariantCulture when serializing dates for storage.


