Nigel Whitworth's Development Site

You are currently not logged in.

Visual Basic.NET Error Handling


In VB6, you had the old error handling system of "ON ERROR...". With .NET, you now have the structured error handling system that is similar to that used in C/C++. Below is an example of how you would implement error handling in VB6.
	sub MiscellaneousFunction()
	      
	     dim objDB as clsDatabase
	
	     on error goto errhandler
	
	     set objDB = new clsDatabase
	     ' Do some work
	     
	exitpoint:
	     ' Clear objects, close any connections.
	    set objDB = nothing
	    exit sub
	errhandler:
	     Select case err.number
		  case 3709
		       ' Display Error Message
		case else
		       ' Handle Unknown Errors
	     End Select
	     goto exitpoint
	end sub
	
With .NET, you use the following code :-
	sub MiscellaneousFunction()
	      
	     dim objDB as clsDatabase
	     
	     try
		set objDB = new clsDatabase
		     
		' Do some work
	
	     catch exc as exception
		  select case exc.number
		       case 3709
		  end select
	     finally
		  set objDB = nothing
	     end try
	end sub
The golden rule is to replace on error goto errhandler with Try, any tidy up code goes after the finally command. The label that was to be place where the error handling code begins is replaced with Catch exc as exception. You can different types of exceptions with different Catch statements such as below :
	try
	
	catch exc as exception.DivideByZero
	     ' Catch only exceptions cause by dividing by zero.
	catch exc as exception
	     ' Catch any exception not already caught.
	finally
	     ' Tidy up
	end try
All variables declarations must be done before the try statement other wise you will not be able to do anything with the variable in the tidy up section. The finally clause will be executed whether an error has occurred or not.

To cause an error in VB6, you use the Err.raise followed by an error number, in VB.NET is different, you need to throw an exception. You can either THROW exc as in the example above or Throw New Exception("") with an error message between the quotes.

VB.NET also enables a user to write an error message to the NT/2000/XP event log, below is example code to write a message to an event log.
	dim objLOG as new eventlog
	
	if not eventLog.SourceExists("Source" then
	     eventlog.createEventSource("Source","Log")
	end if
	
	set objLOG = new eventLog()
	    objLOG.Source="Source"
	    objLOG.WriteEntry("Msg")
	set objLOG = nothing
	



If you intend to vote or make a comment, please enter the security code. CODE

Make a comment

*Comments are the views of individuals, they may or may not be correct.
All comments are reviewed and accepted or rejected.
If you give an email address, you will be sent an email when someone makes a comment on this page.*

Name :
Email :
Comments :


Only name and Code is compulsory.