Skip to content
Visual Basic

Error Handling (Try/Catch)

Structured exception handling in VB.

By EZ4Code Team
errorexceptiontry-catch

Code

Try
    Dim result As Integer = 10  0
Catch ex As DivideByZeroException
    Console.WriteLine("Cannot divide by zero: " & ex.Message)
Catch ex As Exception
    Console.WriteLine("Error: " & ex.Message)
Finally
    Console.WriteLine("Cleanup")
End Try

' Throw
Function ParseAge(s As String) As Integer
    Dim age As Integer
    If Not Integer.TryParse(s, age) Then
        Throw New ArgumentException("Invalid age: " & s)
    End If
    If age < 0 OrElse age > 150 Then
        Throw New ArgumentOutOfRangeException("age", "Must be 0-150")
    End If
    Return age
End Function

' Exception filter (VB 2015+)
Try
    RiskyOp()
Catch ex As IOException When ex.Message.Contains("disk")
    Console.WriteLine("Disk error")
End Try

Explanation

VB uses Try/Catch/Finally like C#. Multiple Catch blocks go from specific to general. When filters (VB 2015+) conditionally catch. Finally always runs (even after Return). Throw without args rethrows in Catch — preserves stack trace. Use specific exceptions (ArgumentException, IOException) over generic Exception.

More Visual Basic Snippets