Error Handling
Error handling is essential in Visual Basic 2015 to prevent crashes and ensure smooth program execution.
24.1 Introduction
Errors occur when users input invalid data or unexpected situations arise. For example, entering text into a numeric field will cause a runtime error.
Proper error handling prevents crashes and improves user experience.
VB2015 can handle some errors automatically. For example:
- Divide by zero → returns Infinity
24.2 On Error GoTo
On Error GoTo error_handler
If an error occurs, the program jumps to the label.
Example
On Error GoTo error_handler
firstNum = TxtNum1.Text
secondNum = TxtNum2.Text
Lbl_Answer.Text = firstNum / secondNum
Exit Sub
error_handler:
Lbl_Answer.Text = "Error"
Figure 24.1
24.3 Try...Catch
Try
statements
Catch ex As Exception
error handling
End Try
Example
Try
firstNum = TxtNum1.Text
secondNum = TxtNum2.Text
answer = firstNum / secondNum
Catch ex As Exception
Lbl_Answer.Text = "Error"
End Try
Figure 24.2
Recommended Upgrade
Build on This Foundation
Continue to VB2026
After learning the basics of checkbox controls in VB2015, move to the newest VB2026 tutorial for a more modern VB.NET learning path.
Visual Basic Programming
Use this Top Release book to reinforce your tutorial learning with a more structured guide.
- Errors must be handled to prevent crashes
- On Error GoTo is older method
- Try...Catch is modern method
- Always validate user input