Click here to Skip to main content
15,867,308 members
Articles / Operating Systems / Windows
Article

VB .NET Error Handling

Rate me:
Please Sign up or sign in to vote.
2.55/5 (19 votes)
2 Apr 2006CPOL7 min read 169.1K   12   11
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:<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.

<o:p> 

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

                          Problem<o:p>

                       Description<o:p>

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:

<o:p>

 

Try<o:p>

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

     Catch<o:p>

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

     Finally<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.

Example:

<o:p> 

         Try<o:p>

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

            prcTextFile.Start ()<o:p>

        Catch<o:p>

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

        Finally<o:p>

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

        End Try<o:p>

<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.

<o:p> 

<o:p>

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:

<o:p> 

(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.

<o:p> 

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.

<o:p> 

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.

<o:p> 

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

<o:p> 

Error Number<o:p>

Default Error Message<o:p>

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

<o:p> 

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>

<o:p> 

Try<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>

        Catch<o:p>

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

        Finally<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>

         Try<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>

        Catch<o:p>

            'Error Handling Logic/Code<o:p>

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

        Finally<o:p>

            'Execution Resumes Here<o:p>

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

        End Try<o:p>

<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:

<o:p> 

If File exists Then<o:p>

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

            prcTextFile.Start ()<o:p>

        Else<o:p>

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

        End If<o:p>

<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>

 

 

License

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


Written By
India India
IT Professional with interests in Software Development, Machine Learning, Data Science, Software Application Architecture.

Comments and Discussions

 
QuestionTrace the coding errors Pin
Member 1152843827-Feb-17 19:10
Member 1152843827-Feb-17 19:10 
GeneralMy vote of 1 Pin
Syed J Hashmi27-Mar-13 7:44
Syed J Hashmi27-Mar-13 7:44 
Questionerror handling for character and integer in text box Pin
Iswandi Abdul Rahman26-Aug-11 15:50
Iswandi Abdul Rahman26-Aug-11 15:50 
Questionerror handling in search using searc button Pin
Iswandi Abdul Rahman26-Aug-11 15:36
Iswandi Abdul Rahman26-Aug-11 15:36 
Hai ,i need advice and help here,In this programme i use 1 button( i name it btnsearch) and 1 textbox(i named it textboxname).The function of this button is use to search data in database and function of textbox is for user fill name. I want to put an error handling which if thefunction cannot search the data in database then it will appear message box inform that info not found. Here is my code.I am using visual studio 2005 & sql 2005 as database .

Private Sub Search_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnsearch.Click
Me.StaffBindingSource.Filter = "NAME = '" & Me.txtsearch.Text & "'"

End Sub

GeneralNested Try..Catch Pin
PeaceTiger6-Dec-10 19:14
PeaceTiger6-Dec-10 19:14 
Generaluse to resume in vb.net Pin
pooran singh niranjan21-Sep-10 23:55
pooran singh niranjan21-Sep-10 23:55 
GeneralMy vote of 1 Pin
dawmail33312-Oct-09 2:11
dawmail33312-Oct-09 2:11 
GeneralMy vote of 1 Pin
Richard J Slade2-Feb-09 2:45
Richard J Slade2-Feb-09 2:45 
GeneralExactly What I Needed Pin
suzmonster5-Dec-07 3:52
suzmonster5-Dec-07 3:52 
GeneralMissing vital information Pin
Steven Campbell3-Apr-06 9:05
Steven Campbell3-Apr-06 9:05 
GeneralRe: Missing vital information Pin
Ujwal Watgule3-Apr-06 17:35
Ujwal 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.