Sep 26, 2009

Error Handling in VB.NET

Visual Basic has three main error handling techniques while writing code.

On Error Go To technique allows you to go to a special section in your code to handle the error and exit gracefully. An example is added below.

Sub CalculateD()

On Error Go To HandleDivisionByZero

Dim a as integer = 0, b as integer = 5

Dim d as decimal = b/a

Console.WriteLine (“B divided by a is = “ & Str(D))

Exit Sub

HandleDivisionByZero:

MessageBox (“Division By Zero. Exiting”)

Exit Sub

End Sub

On Error Resume Next technique is simply ignoring the current statement with the error and start from the next statement directly. An example is below:

Sub ResumeWork()

On Error Resume Next

Dim a as integer, b as integer

a = 5: b= 0

dim c as decimal

c = a /b

Console.Writeline(“Finished”)

End Sub

This subroutine would simply ignore the line where c = a/b even that there is a division by zero and continue to print the word Finished as if there is nothing wrong.

 

The two previous technique were simply the old techniques. However, .NET has introduced the Java old technique of try and catch where you can handle all kind of errors and it is extensible.

Try and Catch techinque is a well structured one and allows for even other vendors like Oracle to introduce their own catch blocks.

An Example of this technique is provided below:

Sub CalculateD()

Dim a as integer = 0, b as integer = 5

Try

Dim d as decimal = b/a

Console.WriteLine (“B divided by a is = “ & Str(D))

Catch MyException as exception

MessageBox (“Division By Zero. Exiting”)

Finally

‘ A Comment The programmer can do whatever cleaning he need here

End Try

End Sub

You can see from this code that the technique does not include jumping as well as you are able to catch the exception and handle it as needed. Oracle for example has added another exception called OracleException to handle errors returned by their own database and display their exact exceptions instead of using the .NET exception.

No comments: