Tutorials » DotNet tutorials »

Traditional Visual Basic error handling and it's .NET equivalents

Difference between old Visual Basic "On Error" and new VB.NET exception handling

If you are coming from Visual Badic background, you will find that the error handling mechanism is totally changed in VB.NET.

Visual Basic provides an error handling mechanism, now called 'un structured error handling'. Typically, you will place a code statement "On Error Goto ErrorHandler" on top of your code block. This means, when an error occurs, jump to the path specified by 'Errorhandler'. See the following sample code :

Sub MyMethod
On Error GoTo ErrorHandler

' code that may raise an error

Exit Sub


' Error handling code
End Sub

In the above sample code, if an error occurs in the method, the program execution will jump to the ErrorHandler block. This saves your program from terminating abnormally and gives an opportunity to log the error details and show friendly message to the user.

Equivalent of On Error in VB.NET and C#

Many programmers coming from Visual Basic to .NET asks this question : "what is the equivalent of On Error in .NET ?". The answer is, there is no direct equivalent. Just for backward compatibility, VB.NET supports the "On Error" statement. This is not available in C#. Even though "On Error" statement is supported in VB.NET, you are strongly encouraged to use the new structured exception handling mechanism provided by the .NET Framework.

The above sample code can be re written in VB.NET as shown below :

Private Sub MyMethod()
' code that can raise an error
Catch ex As Exception
' code to handle the exception.
End Try
End Sub

Read the other articles related 'Exception handling' to find more about the structured exception handling in .NET.

Next Chapter: Custom Exceptions
Previous Chapter: Exception Handling in .NET
More Chapters: .NET Tutorials
More Tutorials: Tutorial Index

Top Contributors
TodayLast 7 Daysmore...

Awards & Gifts

Online Members

Copyright © SpiderWorks Technologies Pvt Ltd., Kochi, India