Lesson 24: Errors Handling

Learn to handle runtime errors gracefully in VB2019

Key Takeaway

Proper error handling prevents application crashes and provides users with helpful feedback. VB2019 offers two approaches: traditional On Error and modern Try-Catch.

Error handling is an essential procedure in Visual Basic 2019 programming. Error-free code not only enables the program to run smoothly and efficiently, but it can also prevent all sorts of problems from happening like program crashes or system hangs. Errors often occur due to incorrect input from the user.

Prevent Crashes

Handle unexpected situations gracefully

User Experience

Provide meaningful feedback to users

Debugging Aid

Identify and log issues during development

Robust Code

Create resilient applications that handle edge cases

24.1 Introduction to Error Handling

Errors often occur due to incorrect input from the user. For example, the user might make the mistake of attempting to enter text (string) to a box that is designed to handle only numeric values such as the weight of a person. The computer will not be able to perform arithmetic calculation for text, therefore creating an error. These errors are known as synchronous errors.

Why Handle Errors?

A good programmer should anticipate parts of the program that could trigger errors and write error handling code to help users manage these situations. Writing error handling code is a good practice for Visual Basic 2019 programmers.

Visual Basic 2019 has improved significantly in its built-in error handling capabilities compared to Visual Basic 6. For example, when the user attempts to divide a number by zero, Visual Basic 2019 will not return an error message but gives 'infinity' as the answer.

Common Error Types

Error Type Description Example
Invalid Cast Converting incompatible data types Converting "ABC" to Integer
Divide By Zero Attempting to divide by zero 10 / 0
Null Reference Accessing properties of Nothing Dim s As String = Nothing
s.Length
Index Out of Range Accessing array elements beyond bounds Dim arr(5) As Integer
arr(6) = 10

24.2 Using On Error GoTo Syntax

Visual Basic 2019 still supports the VB6 error handling syntax, which is the On Error GoTo program_label structure. The syntax for error handling is:

On Error GoTo program_label

Where program_label is the section of code designed to handle the error committed by the user. Once an error is detected, the program will jump to the program_label section for error handling.

Example: Handling Division Errors

In this example, we handle errors when users enter non-numeric data into text boxes that should contain numbers. The program_label here is error_handler.

Form1.vb
Private Sub BtnCal_Click(sender As Object, e As EventArgs) Handles BtnCal.Click
    ' Hide previous error messages
    Lbl_ErrMsg.Visible = False
    
    Dim firstNum, secondNum As Double
    
    ' Set up error handling
    On Error GoTo error_handler
    
    ' Attempt to convert text to numbers
    firstNum = TxtNum1.Text
    secondNum = TxtNum2.Text
    
    ' Perform calculation
    Lbl_Answer.Text = firstNum / secondNum
    
    ' Exit before error handler if successful
    Exit Sub
    
error_handler:
    ' Display error message
    Lbl_Answer.Text = "Error"
    Lbl_ErrMsg.Visible = True
    Lbl_ErrMsg.Text = " One or both of the entries is/are non-numeric! Try again!"
End Sub
Error Handling Interface

Figure 24.1: Handling non-numeric input errors

Note on Division by Zero

In Visual Basic 2019, division by zero no longer throws an exception but returns Double.PositiveInfinity, Double.NegativeInfinity, or Double.NaN (Not a Number). This is different from earlier versions of VB.

24.3 Error Handling with Try-Catch

Visual Basic 2019 has a modern approach to error handling using the Try...Catch...End Try structure. This method is more efficient than the old On Error GoTo approach as it can handle various types of errors within a structured block.

Try
    [ tryStatements ]
[ Catch [ exception [ As type ] ]
    [ catchStatements ]
[ Finally
    [ finallyStatements ] ]
End Try

Example: Modern Error Handling

Here's the same division calculator implemented with Try-Catch:

Form1.vb
Private Sub BtnCal_Click(sender As Object, e As EventArgs) Handles BtnCal.Click
    Lbl_ErrMsg.Visible = False
    Dim firstNum, secondNum, answer As Double
    
    Try
        ' Attempt conversion and calculation
        firstNum = TxtNum1.Text
        secondNum = TxtNum2.Text
        answer = firstNum / secondNum
        Lbl_Answer.Text = answer
    
    Catch ex As Exception
        ' Handle any exceptions
        Lbl_Answer.Text = "Error"
        Lbl_ErrMsg.Visible = True
        Lbl_ErrMsg.Text = " One of the entries is not a number! Try again!"
        
        ' Optional: Log the error for debugging
        ' Debug.WriteLine("Error: " & ex.Message)
    End Try
End Sub
Try-Catch Error Handling

Figure 24.2: Error handling with Try-Catch

Benefits of Try-Catch

  • Structured Handling: Errors are contained within specific blocks
  • Multiple Exception Types: Catch different exceptions with multiple Catch blocks
  • Resource Cleanup: Use Finally block to release resources regardless of errors
  • Modern Approach: Aligns with error handling in other .NET languages
  • Detailed Information: Exception objects contain detailed error information

Handling Specific Exceptions

You can catch specific types of exceptions to handle different error scenarios appropriately:

Form1.vb
Try
    ' Code that might cause different exceptions
    
Catch ex As InvalidCastException
    ' Handle invalid type conversions
    MessageBox.Show("Please enter numeric values only")
    
Catch ex As DivideByZeroException
    ' Handle division by zero
    MessageBox.Show("Cannot divide by zero")
    
Catch ex As Exception
    ' Handle all other exceptions
    MessageBox.Show("An unexpected error occurred: " & ex.Message)
    
Finally
    ' Code that always runs (cleanup resources, etc.)
    ' e.g., connection.Close()
End Try

Lesson Summary

In this lesson, you've learned how to handle errors in VB2019:

Error Types

Understand common runtime errors like invalid casts and division by zero

Traditional Approach

Implement error handling using On Error GoTo syntax

Modern Approach

Use Try-Catch blocks for structured exception handling

Specific Exceptions

Handle different error types with multiple Catch blocks

Proper error handling is essential for creating robust, user-friendly applications. In the next lesson, we'll explore object-oriented programming in VB2019.

Next Lesson

Learn object-oriented programming concepts 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

VB2019 Paperback

Comprehensive guide to Visual Basic 2019

Get on Amazon