Error Handling in VB.NET

A small tutorial with Code Source to handle errors and exceptions in

Project details:
1- New solution for handling errors in .net
2- Try...Catch...Finally Block
3- Error handling sample

1- New solution for handling errors in .net

Errors handling had been improved with the new .net. The Try...End try block can minimize code and simplify it.
However some old methods still alive with the .net 2.0 which can be useful sometimes.
There's also some changes that we'll discuss.
From the first Visual Basic edition and also I remember it on QBasic, there was a method to handle errors which is "On Error".
Now the method still exist but replace with the new Try...End try block.
In error raising we'll use the Throw command.

2- Try...Catch...Finally Block

The Try...Catch...Finally Block structure

Here's the code where you want to monitor for errors

When an error occurs, the application will jump immediately to this section.

This step is optional, but if defined it'll run whatever an error occur or not.
Generally we use it to close an opened file or connection

There can be different types of errors.
This structure allows you to handle each type alone.

' ----- The Code is here.
Catch ex As System.OutOfMemoryException
' ----- Handle memory errors here.
Catch ex As System.Exception
----- Handle all other errors here.
End Try

You can do more customization for the Catch block and this shows how much the .net is flexible.
Let understand how this was done.
The integer is empty when we start running the code. Now we go to step 1, the integer contain 1. If an error occur, the application will stop processing and jump to the Catch blocks. Each block to choose? ;)

Dim Step as integer
' ----- The Code is here.
Step = 1
Step = 2
Catch ex As Exception When Step = 1
' ----- Handle
the step 1 errors
Catch ex As Exception When Step = 2
' ----- Handle the
step 2 errors
End Try

3- Error handling sample

The sample is simple!
There's two text boxes, you have to fill both of them with numbers. By pressing the button you'll divide them.
When the problem can occur?

Dim a As Integer = CInt(TextBox1.Text) 'Here when converting
Dim b As
Integer = CInt(TextBox2.Text) 'Here when converting
TextBox3.Text = a / b
'When dividing by Zero or big numbers (out of capacities)

How to handle those errors?
Check out the sample to know how we can do it. The sample is commented and explanation is inside.

Subscribe to get the latest tutorials
Download the tutorial

The Zip file contains:
-The sample source code
-The readme.txt file
-The tutorial.txt file
By Omar Abid   Popularity  (1759 Views)