Sometimes, we encounter different errors along the program whenever we executed it. For example, the file does not exist in the given path, network connections are not connected, or any errors that you have experienced when you're learning how to program. This is what we've called Runtime Errors. One way to prevent it is the Structured exception handling.
In this tutorial, we will used the Try-Catch-Finally statement. This control structure tests a piece of code, filters exceptions created by the execution of that code, and reacts differently based on the type of thrown exception.
Now lets start this tutorial! :)
1. Let's start with creating a Windows Form Application for this tutorial by following the following steps in Microsoft Visual Studio: Go to File, click New Project, and choose Windows Application.
2. Next, add a Button named Button1 labeled as Compute, and lastly add two textboxes named TextBox1 and TextBox2. You must design your layout like this:
3. In your code module, code this for your Button1_Click:
- Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
- Dim num1 As Integer, num2 As Integer
- Dim result As Integer = 0
- num1 = Val(TextBox1.Text)
- num2 = Val(TextBox2.Text)
- result = num1 / num2
- MsgBox("The answer is " & result)
- Catch ex As Exception
- MsgBox("Cannot be divided by 0.")
- MsgBox("Thank you for using this application")
- End Try
- End Sub
We have now created our Try-Catch-Finally statement. In the try block, we code for it if there is no error when we run the program. We have initialized num1 and num2 as integer to hold the value of textbox1 and textbox2 respectively. Then we initialized result as integer to get the quotient of our num1 and num2. Then after it, it will exit from the Try Block. Next, in the Catch Block if the exception occurred or have an error, this catch block code will execute and will prompt the user "Cannot be divided by 0.". The code in the finally block will execute even if there is no Exceptions. That means if you write a finally block , the code should execute after the execution of try block or catch block.
Output: The try block
Output: The catch block
Output: The finally block
Download the source code below and try it! :)
For more inquiries and need programmer for your thesis systems in any kind of programming languages, just contact my number below.
Engr. Lyndon R. Bermoy
IT Instructor/System Developer/Android Developer
STI College - Surigao City
Follow and add me in my Facebook Account: https://www.facebook.com/donzzsky
Visit and like my page on Facebook at: https://www.facebook.com/BermzISware