Exception Handling

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: design 3. In your code module, code this for your Button1_Click:
  1. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
  2. Try
  3. Dim num1 As Integer, num2 As Integer
  4. Dim result As Integer = 0
  5. num1 = Val(TextBox1.Text)
  6. num2 = Val(TextBox2.Text)
  7. result = num1 / num2
  8. MsgBox("The answer is " & result)
  9. Catch ex As Exception
  10. MsgBox("Cannot be divided by 0.")
  11. Finally
  12. MsgBox("Thank you for using this application")
  13. End Try
  14. 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.


The try block output


The catch block output


The finally block output 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. Best Regards, Engr. Lyndon R. Bermoy IT Instructor/System Developer/Android Developer STI College - Surigao City Mobile: 09488225971 E-mail:[email protected] 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

Add new comment