Saturday, October 14, 2006

Error Handiling in VB.NET

Sell and Buy Used Book - Bukz4u.com
Error handiling in VB.NET is done using error handling structure called Try...Catch...Finally, old versions like vb6 uses On Error Goto structure for error handiling.

The overall structure of the Try...Catch...Finally syntax is to put the code that might cause an error in the Try portion,and then catch the error. Inside the Catch portion, you handle the error. The Finally portion runs code that happens after the Catch statements are done, regardless of whether or not there was an error.

Example:


Dim x, y As Integer
x=2
y=0

Try

x \= y

Catch ex As Exception

msgbox(ex.Message)

End Try


Tip:: ex As Exception part of the Catch statement is optional.

In the above code you have two variables of type integers. You attempted to divide x by y, but because y has value set to 0. That division by zero raises an error, and you catch it in the next line. The variable ex is of type Exception, which holds the error that just occurred, so you simply print the Message property.