Lesson 24: Mastering Errors Handling in VB2022

Build robust applications by learning structured exception handling techniques

Key Takeaway

Effective error handling prevents application crashes, provides meaningful feedback to users, and ensures your VB2022 applications run smoothly even under unexpected conditions.

Welcome to Lesson 24 of our Visual Basic 2022 Tutorial! In this lesson, you'll master the art of error handling in VB2022. While we all strive to write perfect code, errors are inevitable in real-world applications. Learning to handle them gracefully is what separates amateur from professional developers.

24.1 Why Error Handling is Essential

Error handling is critical for creating robust applications that can handle unexpected situations without crashing. Common causes of errors include:

User Input Errors

Non-numeric input in numeric fields, invalid formats, or unexpected values

File Access Issues

Missing files, permission problems, or locked resources

Resource Limitations

Insufficient memory, disk space, or network connectivity issues

24.2 Using On Error GoTo Syntax

Visual Basic 2022 supports the traditional VB6 error handling syntax using On Error GoTo. This approach is still useful for compatibility or specific scenarios.

1 Syntax Structure

The basic structure for traditional error handling:

On Error GoTo ErrorLabel
' Code that might cause an error
Exit Sub

ErrorLabel:
' Error handling code
Resume Next

2 Error Handler

The labeled section contains code to handle errors and provide feedback

3 Resume Options

Use Resume, Resume Next, or Resume Line to control program flow after errors

Example 24.1: Handling Non-Numeric Input

This example uses On Error GoTo to handle invalid input:

DivisionCalculator.vb
Private Sub BtnCalculate_Click(sender As Object, e As EventArgs) Handles BtnCalculate.Click
    LblErrorMessage.Visible = False
    Dim num1, num2, result As Double

    ' Activate error handling
    On Error GoTo ErrorHandler

    num1 = CDbl(TxtNumber1.Text)
    num2 = CDbl(TxtNumber2.Text)
    
    ' Explicit check for division by zero
    If num2 = 0 Then
        Err.Raise(11) ' Division by zero error
    End If

    result = num1 / num2
    LblResult.Text = result.ToString("N2")

    ' Exit before error handler
    Exit Sub

ErrorHandler:
    ' Handle specific error types
    Select Case Err.Number
        Case 6 ' Overflow
            LblErrorMessage.Text = "Number too large or too small"
        Case 11 ' Division by zero
            LblErrorMessage.Text = "Cannot divide by zero"
        Case 13 ' Type mismatch
            LblErrorMessage.Text = "Please enter valid numbers"
        Case Else
            LblErrorMessage.Text = $"Unexpected error: {Err.Description}"
    End Select

    LblErrorMessage.Visible = True
    LblResult.Text = "Error"
    Resume Next
End Sub

Error Handling Preview

Division Calculator

Input 1: 10

Input 2: abc

Result: Error

Error: Please enter valid numbers

24.3 Modern Error Handling with Try-Catch

VB2022 provides a more structured approach to error handling with Try...Catch...Finally. This method is preferred for its flexibility and clarity.

Block Description Usage
Try Contains code that might cause exceptions Wrap potentially problematic code
Catch Handles specific exception types Catch ex As ExceptionType
Finally Always executes for cleanup operations Release resources like file handles
When Adds conditions to catch blocks Catch ex When condition

Example 24.2: Basic Try-Catch Block

This example demonstrates structured exception handling:

FileReader.vb
Private Sub BtnReadFile_Click(sender As Object, e As EventArgs) Handles BtnReadFile.Click
    Dim fileReader As System.IO.StreamReader = Nothing
    
    Try
        ' Attempt to open and read file
        fileReader = New System.IO.StreamReader("C:\data\important.txt")
        TxtContent.Text = fileReader.ReadToEnd()
        LblStatus.Text = "File read successfully"
        
    Catch ex As System.IO.FileNotFoundException
        LblStatus.Text = "File not found"
        MessageBox.Show("The file was not found: " & ex.Message, "File Error", 
                        MessageBoxButtons.OK, MessageBoxIcon.Error)
        
    Catch ex As System.IO.IOException
        LblStatus.Text = "I/O Error"
        MessageBox.Show("An I/O error occurred: " & ex.Message, "I/O Error", 
                        MessageBoxButtons.OK, MessageBoxIcon.Error)
        
    Catch ex As Exception
        LblStatus.Text = "General Error"
        MessageBox.Show("An unexpected error occurred: " & ex.Message, "Error", 
                        MessageBoxButtons.OK, MessageBoxIcon.Error)
        
    Finally
        ' Ensure file is closed even if error occurred
        If fileReader IsNot Nothing Then
            fileReader.Close()
        End If
    End Try
End Sub

Pro Tip: Exception Hierarchy

Catch blocks are evaluated from most specific to most general. Always place specific exception types before the general Exception type.

24.4 Handling Specific Exceptions

VB2022 provides specific exception classes for different error types. Handling them separately allows for more precise error recovery.

FormatException

Invalid format conversion (e.g., converting text to number)

DivideByZeroException

Division by zero in numeric operations

OverflowException

Value too large or too small for data type

Example 24.3: Handling Multiple Exception Types

This example shows how to handle different exceptions separately:

TemperatureConverter.vb
Private Sub BtnConvert_Click(sender As Object, e As EventArgs) Handles BtnConvert.Click
    LblErrorMessage.Visible = False
    
    Try
        Dim fahrenheit = CDbl(TxtFahrenheit.Text)
        
        ' Validate temperature range
        If fahrenheit < -459.67 Then
            Throw New ArgumentOutOfRangeException("Temperature below absolute zero")
        End If
        
        Dim celsius = (fahrenheit - 32) * 5 / 9
        LblCelsius.Text = celsius.ToString("N1") & " °C"
        
    Catch ex As FormatException
        LblErrorMessage.Text = "Please enter a valid number"
        LblErrorMessage.Visible = True
        
    Catch ex As OverflowException
        LblErrorMessage.Text = "Number is too large or too small"
        LblErrorMessage.Visible = True
        
    Catch ex As ArgumentOutOfRangeException
        LblErrorMessage.Text = "Temperature cannot be below absolute zero (-459.67°F)"
        LblErrorMessage.Visible = True
        
    Catch ex As Exception
        LblErrorMessage.Text = $"Unexpected error: {ex.Message}"
        LblErrorMessage.Visible = True
        
    End Try
End Sub

24.5 Using the Finally Block

The Finally block is essential for cleanup operations. It executes whether an exception occurs or not.

1 Resource Cleanup

Close files, database connections, or release other resources

2 State Reset

Reset UI elements or application state after operations

3 Guaranteed Execution

Code in Finally runs even if exceptions occur or returns happen

Example 24.4: Database Connection Cleanup

This example shows proper resource cleanup using Finally:

DatabaseAccess.vb
Private Sub LoadCustomerData()
    Dim conn As New SqlConnection("connection_string")
    Dim cmd As New SqlCommand("SELECT * FROM Customers", conn)
    Dim reader As SqlDataReader = Nothing
    
    Try
        conn.Open()
        reader = cmd.ExecuteReader()
        
        ' Process data
        While reader.Read()
            ' Add data to list
        End While
        
    Catch ex As SqlException
        MessageBox.Show($"Database error: {ex.Message}", "Database Error", 
                      MessageBoxButtons.OK, MessageBoxIcon.Error)
        
    Catch ex As Exception
        MessageBox.Show($"General error: {ex.Message}", "Error", 
                      MessageBoxButtons.OK, MessageBoxIcon.Error)
        
    Finally
        ' Cleanup resources in reverse order of creation
        If reader IsNot Nothing AndAlso Not reader.IsClosed Then
            reader.Close()
        End If
        
        If conn.State = ConnectionState.Open Then
            conn.Close()
        End If
        
        ' Dispose of objects
        reader?.Dispose()
        cmd.Dispose()
        conn.Dispose()
        
        LblStatus.Text = "Operation completed"
    End Try
End Sub

Error Handling Summary

Master these essential error handling techniques in VB2022:

Technique Description When to Use
On Error GoTo Traditional VB error handling Compatibility with legacy code
Try-Catch-Finally Structured exception handling Modern applications, resource cleanup
Specific Exceptions Handling particular error types Precise error recovery
Custom Exceptions User-defined exception classes Domain-specific error handling
Exception Properties Message, StackTrace, InnerException Debugging and logging

Best Practices

Always release resources in Finally blocks, provide meaningful error messages, and log exceptions for debugging.

Defensive Programming

Validate inputs and check preconditions to prevent errors before they occur.

User Experience

Display user-friendly messages while logging technical details for developers.

Practical Exercises

Apply your error handling knowledge with these hands-on exercises:

Exercise 1: Input Validation

Create an age verification form that handles non-numeric input, negative values, and unreasonably high ages using specific exception handling.

Exercise 2: File Operations

Write a program that reads a CSV file and handles file not found, access denied, and format errors with appropriate messages.

Exercise 3: Custom Exceptions

Create a custom InvalidEmailException class and use it in a registration form to validate email formats.

Exercise 4: Finally Block Practice

Implement a database connection wrapper that ensures connections are always closed using a Finally block.

Exercise 5: Error Logging

Extend any of the previous exercises to log errors to a text file with timestamps and stack traces.

Next Lesson

Learn object-oriented programming fundamentals in Lesson 25: Object-Oriented Programming.

Related Resources

VB6 Tutorial

Mastering VB6 Programming

Explore Tutorials

Visual Basic Examples

Practical VB code samples for real-world applications

View Examples

Excel VBA Tutorial

Learn how to automate Excel by creating VBA macros

Learn More