Error handling is an essential procedure in Visual Basic programming because it can help make the program error-free. An error-free program can run smoothly and efficiently, and the user does not have to face all sorts of problems such as program crash or system hang.
Errors often occur due to incorrect input from the user. For example, the user might make the mistake of attempting to ask the computer to divide a number by zero which will definitely cause system error. Another example is the user might enter a 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 will create an error. These errors are known as synchronous errors.
Therefore a good programmer should be more alert to the parts of program that could trigger errors and should write errors handling code to help the user in managing the errors. Writing errors handling code should be considered a good practice for Visual Basic programmers, so do try to finish a program fast by omitting the errors handling code. However, there should not be too many errors handling code in the program as it create problems for the programmer to maintain and troubleshoot the program later.
Writing the Errors Handling Code :
We shall now learn how to write errors handling code in Visual Basic. The syntax for errors handling is
On Error GoTo program_label
where program_label is the section of code that is designed by the programmer 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. It acts like a bookmark in VB
Intro : This code shows how to handle error 'Division By Zero'.
Private Sub CmdCalculate_Click() Dim firstNum, secondNum As Double firstNum = Txt_FirstNumber.Text secondNum = Txt_SecondNumber.Text On Error GoTo error_handler Lbl_Answer.Caption = firstNum / secondNum Exit Sub 'To prevent error handling even the inputs are valid error_handler: Lbl_Answer.Caption = "Error" Lbl_ErrorMsg.Visible = True Lbl_ErrorMsg.Caption = " You attempt to divide a number by zero!Try again!" End Sub
The line 'On Error GoTo error_handler' gets executed when there occurs an error in DIVISION.
When we input secondnum=0 then the line returns an error. then the 'error_handler' section of code is executed, simple.
NOTE : IT may be noticed that if there is no error , the error handling part of code is NOT executed due to use of EXIT SUB.
Was'nt that easy, handling errors?