Click here to Skip to main content
15,354,402 members
Articles / Operating Systems / Windows
Posted 2 Apr 2006


12 bookmarked

VB .NET Error Handling

Rate me:
Please Sign up or sign in to vote.
2.94/5 (18 votes)
2 Apr 2006CPOL7 min read
Introductory tutorial on Visual Basic error handling


In this article, you’ll learn how to build blocks of code that handle run time errors, also referred as exceptions which occur as a result of normal operating conditions for example. Errors due to a disk not being in the drive or to an offline printer.

Visual Basic .NET includes the Try---Catch code block, a new syntax for handling error. In this article you’ll learn how to trap run time errors using Try---Catch code block, and you’ll learn how to use the Err.Number and Err.Description properties to identify specific runtime errors. You’ll also learn how to use multiple Catch statements to write more flexible error handlers, build nested Try---Catch code blocks, and use the Exit Try statement to exit a Try --- Catch code block prematurely.


2.Processing Errors Using Try - - - Catch:<o:p>

A runtime error, or program crash, is an unexpected problem in a Visual Basic program from which the program can’t recover. It’s not that Visual Basic don’t smart enough to handle the glitch; it’s just that Visual Basic hasn’t been told what to do when something goes wrong.

Fortunately you don’t have to live with the occasional errors that cause your programs to crash. You can write special Visual Basic runtimes, called structured error handlers, to respond to runtime errors. An error handler handles a runtime error by telling the program how to continue when one of its statements doesn’t work. Error handlers are placed in the event procedures, in which there is a potential for trouble, or in generic functions or subprograms that handle errors for you systematically. As their name implies, error handlers handle, or trap, a problem by using the Try --- Catch statements and a special error handling object Err. The Err object has a Number property that identifies the error number and a Description property that allows you to print a description of the error.


3.When to Use Error Handlers:<o:p>

You can use error handlers in any situation in which an expected or an unexpected action might result in an error that stops program execution. Typically, error handlers are used to process external events that influence a program – for example, events caused by a failed network or Internet connection, a disk not being in the floppy drive, or an offline printer. The Following table lists potential problems that can be addressed by error handlers



Network/Internet Problems<o:p>

Network servers, modems or resources that fail, or go down, unexpectedly.

Disk drive problems

Unformatted or incorrectly formatted disks, disk that aren’t properly inserted, bad disk sectors, disks that are full, problems with CD-ROM drives, and so on.

Path Problems

A path to a necessary file is missing or incorrect.

Printer Problems

Printers that are offline, out of paper, out of memory, or otherwise unavailable.

Software not installed

A file or component that your application relies on is not installed on user’s computer, or there’s an operating system incompatibility.

Permission Problems

The user doesn’t have the appropriate permissions to perform a task.

Overflow Errors

An activity that exceeds the allocated memory space.

Out-of-Memory errors

Application or resource space that’s not available in Microsoft Windows.

Clipboard Problems

Problems with data transfer or Windows clipboard.

Logic Errors

Syntax or logic error undetected by the compiler


4.The Try --- Catch Statement:<o:p>

The basic syntax for Try - - - Catch exception handler is simply the following:

The Try Statement identifies the beginning of an error handler:




       'Statements that might produce a runtime error<o:p>


       'Statements to run if runtime errors occur<o:p>


       'Optional statements to run whether an error occur or not<o:p>

     End Try


The statement between the Try – Catch keywords is called protected code because any runtime errors resulting from these statements won’t cause the program to crash.




            prcTextFile.StartInfo.FileName = ("C:\Program               Files\ErrorHandler\VbNetError.txt ")<o:p>

            prcTextFile.Start ()<o:p>


            MessageBox.Show ("Unable to locate the desired file")<o:p>


            MessageBox.Show ("Error Handler Complete")<o:p>

        End Try<o:p>


In a real program you’ll probably want to use the Finally code block to update important variables or properties, display data, or perform other cleanup operations.



5.More Complex Try --- Catch Error Handlers:<o:p>

As your program become more sophisticated, you might find it useful to write more complex Try --_ Catch error handlers that manage a variety of runtime errors and unusual error handling situations.Try --- Catch provides for this complexity by:


(1). Permitting multiple lines of code in each Try, Catch or Finally code block.

(2). Offering the Catch When syntax, which tests specific error conditions.

(3). Allowing nested Try --- Catch code block, which can be used to build sophisticated and robust error handlers.


In addition a special error handling object named Err allows you to identify and process runtime errors and conditions in your program.


6.The Err Object:<o:p>

Err  is a special Visual Basic object that’s assigned detailed error handling information each time a runtime error occurs. The most useful Err properties for identifying runtime errors are Err.Number and Err.Description.


Err.Number: contains the number of the most recent runtime error.

Err.Description: a short error message that matches the runtime error numbers.

By using the Err.Number and Err.Description properties together in an error handler, you can recognize specific errors and respond to them and you can give the user helpful information about how he or she should respond.


The Following table lists many of the runtime errors that Visual Basic application can encounter:


Error Number<o:p>

Default Error Message<o:p>


Procedure call or argument is not valid




Out of Memory


Division by Zero


Internal Error


Bad file name or number


File not found


File already open


Path not found


Printer error


For more information on a particular error, search for Visual Studio online Help. Unused error numbers in the range of 1-1000 are reserved for future use by Visual Basic.NET.


7.Test for Multiple Runtime Errors:<o:p>



            prcTextFile.StartInfo.FileName = ("C:\Program Files\ErrorHandler\VbNetError.txt ")<o:p>

            prcTextFile.Start ()<o:p>

        Catch When Err. Number = 53 'If File Not Found Error<o:p>

            MessageBox.Show ("Unable to locate the desired file")<o:p>

        Catch When Err. Number = 7 'If Out of Memory Error<o:p>

            MessageBox.Show ("Are you sure about the file Path")<o:p>


            MessageBox.Show ("Problem Loading File")<o:p>


            MessageBox.Show ("Error Handler Complete")<o:p>

        End Try<o:p>


8.Exit Try:<o:p>

As with any block structure, it is very nice to be able to jump out of the structure when needed. This is the purpose of the Exit Try statement.

If we have a Finally block that block’s code must be run before the Try block is exited.<o:p>


            'Any Protected Code<o:p>

            prcTextFile.StartInfo.FileName = ("C:\Program Files\ErrorHandler\VbNetError.txt ")<o:p>

            prcTextFile.Start ()<o:p>

            If blnFlg = True Then Exit Try<o:p>


            'Error Handling Logic/Code<o:p>

            MessageBox.Show ("Unable to locate the desired file")<o:p>


            'Execution Resumes Here<o:p>

            MessageBox.Show ("Error Handler Complete")<o:p>

        End Try<o:p>


Based on the flow of your code, you can jump out of the protected region at any point with the Exit Try statement.


9.Error Handlers and Defensive Programming Techniques:<o:p>

Consider the following piece of code:


If File exists Then<o:p>

            prcTextFile.StartInfo.FileName = ("C:\Program Files\ErrorHandler\VbNetError.txt ")<o:p>

            prcTextFile.Start ()<o:p>


            MessageBox.Show ("File Not Found")<o:p>

        End If<o:p>


This If---Then statement isn’t an actual error handler because it doesn’t prevent a runtime error from halting a program. Instead, it’s a validation technique that some programmers call Defensive Programming.<o:p>

In this particular case, testing to see whether a file exists with a .NET framework method is actually faster than waiting for Visual Basic to issue an exception and recover from an runtime error using an error handler. When should you use defensive programming techniques and when should you use error handlers? The answer depends on how often you think a problem will occur with the statements you plan to use. If there’s a real likelihood that a piece of code will produce a runtime error more than 25 percent time, defensive programming logic is usually the most efficient way to manage potential problems.<o:p>


10. Conclusion:<o:p>

Thus Visual Basic .NET offers very flexible error handling technique. I hope this article guides beginners about implementing error handling in their application. <o:p>




This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Ujwal Watgule
Team Leader
India India
Hello Reader, This is Ujwal working with a consultancy firm. I develope applications in Microsoft .NET Technologies.

Comments and Discussions

QuestionTrace the coding errors Pin
Member 1152843827-Feb-17 19:10
MemberMember 1152843827-Feb-17 19:10 
GeneralMy vote of 1 Pin
Syed Javed27-Mar-13 7:44
MemberSyed Javed27-Mar-13 7:44 
Questionerror handling for character and integer in text box Pin
Iswandi Abdul Rahman26-Aug-11 15:50
MemberIswandi Abdul Rahman26-Aug-11 15:50 
Questionerror handling in search using searc button Pin
Iswandi Abdul Rahman26-Aug-11 15:36
MemberIswandi Abdul Rahman26-Aug-11 15:36 
GeneralNested Try..Catch Pin
PeaceTiger6-Dec-10 19:14
MemberPeaceTiger6-Dec-10 19:14 
Generaluse to resume in Pin
pooran singh niranjan21-Sep-10 23:55
Memberpooran singh niranjan21-Sep-10 23:55 
GeneralMy vote of 1 Pin
dawmail33312-Oct-09 2:11
Memberdawmail33312-Oct-09 2:11 
GeneralMy vote of 1 Pin
Richard J Slade2-Feb-09 2:45
MemberRichard J Slade2-Feb-09 2:45 
GeneralExactly What I Needed Pin
suzmonster5-Dec-07 3:52
Membersuzmonster5-Dec-07 3:52 
GeneralMissing vital information Pin
Steven Campbell3-Apr-06 9:05
MemberSteven Campbell3-Apr-06 9:05 
You seem to have missed the "Catch ex as Exception" style of handling errors. Its much more descriptive than "Catch When". It is very uncommon for .NET applications to use error numbers as part of the logic, although I could see how it could happen a lot with code ported from VB6.

You have also ommitted how to "throw" errors, and a discussion of call stacks, as it relates to re-throwing errors.

Advice: Perhaps the article would get higher ratings if it was nicely formatted, and the language was less like a MSDN-help article.

my blog
GeneralRe: Missing vital information Pin
Ujwal Watgule3-Apr-06 17:35
MemberUjwal Watgule3-Apr-06 17:35 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.