Click here to Skip to main content
Click here to Skip to main content

VB .NET Error Handling

, 2 Apr 2006 CPOL
Rate this:
Please Sign up or sign in to vote.
Introductory tutorial on Visual Basic error handling

Introduction

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:

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:

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

                          Problem

                       Description

Network/Internet Problems

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:

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

The Try Statement identifies the beginning of an error handler:

 

Try

       'Statements that might produce a runtime error

     Catch

       'Statements to run if runtime errors occur

     Finally

       'Optional statements to run whether an error occur or not

     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.

Example:

 

         Try

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

            prcTextFile.Start ()

        Catch

            MessageBox.Show ("Unable to locate the desired file")

        Finally

            MessageBox.Show ("Error Handler Complete")

        End Try

 

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:

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:

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

Default Error Message

5

Procedure call or argument is not valid

6

Overflow

7

Out of Memory

11

Division by Zero

51

Internal Error

52

Bad file name or number

53

File not found

55

File already open

76

Path not found

482

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:

 

Try

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

            prcTextFile.Start ()

        Catch When Err. Number = 53 'If File Not Found Error

            MessageBox.Show ("Unable to locate the desired file")

        Catch When Err. Number = 7 'If Out of Memory Error

            MessageBox.Show ("Are you sure about the file Path")

        Catch

            MessageBox.Show ("Problem Loading File")

        Finally

            MessageBox.Show ("Error Handler Complete")

        End Try

 

8.Exit Try:

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.

         Try

            'Any Protected Code

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

            prcTextFile.Start ()

            If blnFlg = True Then Exit Try

        Catch

            'Error Handling Logic/Code

            MessageBox.Show ("Unable to locate the desired file")

        Finally

            'Execution Resumes Here

            MessageBox.Show ("Error Handler Complete")

        End Try

 

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:

Consider the following piece of code:

 

If File exists Then

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

            prcTextFile.Start ()

        Else

            MessageBox.Show ("File Not Found")

        End If

 

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.

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.

 

10. Conclusion:

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

 

 

License

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

Share

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

 
GeneralMy vote of 1 PinmemberSyed Javed27-Mar-13 8:44 
Questionerror handling for character and integer in text box PinmemberIswandi Abdul Rahman26-Aug-11 16:50 
Questionerror handling in search using searc button PinmemberIswandi Abdul Rahman26-Aug-11 16:36 
GeneralNested Try..Catch PinmemberPeaceTiger6-Dec-10 20:14 
Generaluse to resume in vb.net Pinmemberpooran singh niranjan22-Sep-10 0:55 
GeneralMy vote of 1 Pinmemberdawmail33312-Oct-09 3:11 
GeneralMy vote of 1 PinmemberRichard J Slade2-Feb-09 3:45 
GeneralExactly What I Needed Pinmembersuzmonster5-Dec-07 4:52 
GeneralMissing vital information PinmemberSteven Campbell3-Apr-06 10: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 PinmemberUjwal Watgule3-Apr-06 18:35 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.141220.1 | Last Updated 2 Apr 2006
Article Copyright 2006 by Ujwal Watgule
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid