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 TryExplanation
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
Variables and Types
Declare variables with Dim and type inference.
Loops and Iteration
For, For Each, While, and Do loops in VB.
Sub and Function Procedures
Define Sub (no return) and Function (returns value).
Windows Forms Basics
Create a simple WinForms application.
File I/O
Read/write text files and use My.Computer.FileSystem.
Collections (List, Dictionary)
Generic collections in VB.NET.