Error Handling in Vb


of 7

Please download to get full document.

View again

All materials on our website are shared by users. If you have any questions about copyright issues, please report us to resolve them. We are always happy to assist you.
Visual Basic .NET or Visual Basic 2005 supports two different ways to keep an unexpected error from terminating an application: unstructured error handling and structured error handling. These events are run-time errors--also called exceptions-- that are responses to abnormal or exceptional conditions that are caused by the execution of a block of code. Unstructured error handling is the name that is used in Visual Basic .NET or Visual Basic 2005 to refer to the error handling method that is use
  Visual Basic .NET or Visual Basic 2005 supports two different ways to keep an unexpectederror from terminating an application: unstructured error handling and structured errorhandling. These events are run-time errors--also called exceptions-- that are responses toabnormal or exceptional conditions that are caused by the execution of a block of code.Unstructured error handling is the name that is used in Visual Basic .NET or Visual Basic2005 to refer to the error handling method that is used in Microsoft Visual Basic 6.0.Structured error handling is introduced for the first time to Visual Basic programmers in.NET and is performed by using the Try...Catch...Finally statement, which has long been afeature of other programming languages. Structured error handling introduces a simpler wayto create and maintain programs with robust, comprehensive error handlers.Although Visual Basic .NET or Visual Basic 2005 supports both methods, the methodscannot be implemented simultaneously in the same procedure. The only exception to this isthe Error statement, which can be used in structured error handling. It is recommended thatall error handling in Visual Basic .NET or Visual Basic 2005 be performed with structurederror handling. Unstructured error handling can degrade the performance of the applicationand result in code that is difficult to debug and maintain.In the case of a run-time error, both error handling methods look for a local error handler thatis defined in a particular block of code. If no local error handler is present, the exception ispropagated up the call stack, until a matching handler is found. The call stack represents allprocedures that have been called prior to the current point of execution and have not yet beenterminated. If no handler is found in the procedures in the call stack when an error occurs, theapplication is terminated. Unstructured Error Handling Unstructured error handling is implemented with the On Error statement, which is placed atthe beginning of a code block to handle all possible exceptions that occur during theexecution of the code. All Visual Basic 6.0 error handlers in .NET are objects that can beaccessed by using the Microsoft.VisualBasic.Information.Err namespace. The handler isset to Nothing each time the procedure is called. You should place only one On Error  statement in each procedure, because additional statements disable all previous handlers thatare defined in that procedure. On Error Statement The On Error statement is used to enable an error-handling routine, disable an errorhandling routine, or specify where to branch the code in the event of an error.   On Error { GoTo [ line | 0 | -1 ] | Resume Next } GoTo line  Used to enable the error-handling routine, starting at the location that is specified by the line  argument. The line argument can be either a line label or a line number that is located withinthe closing procedure. A run-time error activates the error handler and branches the control tothe specified line. If the specified line is not located within the same procedure as the OnError statement, a compile error occurs.   To avoid unexpected behavior, place an Exit Sub statement, an Exit Function statement, oran Exit Property statement just before the line label or line number. This prevents the error-handling code from running when no error has occurred. GoTo 0  Disables the enabled error handler that is defined within the current procedure and resets it to Nothing . GoTo -1  Disables the enabled exception that is defined within the current procedure and resets it to Nothing . Resume Next  Moves the control of execution to the statement that follows immediately after the statementthat caused the run-time error to occur, and continues the execution from this point forward.This is the preferred form to use to access objects, rather than using the On Error GoTo  statement. Example  In the following example code, the error handler is enabled on the first line of the routinewith the On Error GoTo Unstructured statement. The location of the error handling routineis identified with the Unstructured line label. The error routine implements a simple SelectCase statement that executes the corresponding block of code, depending on the error thatoccurred.The Resume Next statement at the end of the error handling procedure returns control of theexecution back to the line that follows the line that caused the error to occur.The error handler is then disabled with the On Error GoTo 0 statement, followed by the OnError Resume Next statement, which reactivates the error handler. If a run-time erroroccurs, the statement causes the execution to branch to the line that immediately follows theline that caused the error to occur, the same way that the Resume Next statement does in theerror handling routine. In this case, that line is the If  statement that evaluates the errornumber and displays it to the user, as well as clearing the error object. Public Sub fnErrors()On Error GoTo Unstructured ' Enable error handlerDim Result As IntegerDim Value1 As Integer = 9Dim Value2 As Integer = 0On Error GoTo 0 ' Disables the error handler'Moves execution to the line following the line that caused the error.On Error Resume NextResult = Value1 / Value2 ' Division by zero, cause an overflow error.  ' Catch the overflow error caused by dividing by zero.If Err.Number = 6 ThenMessageBox.Show( Error Number: & Err.Number.ToString)Err.Clear() ' Clear ErrorsEnd IfExit SubUnstructured: ' Location of error handlerSelect Case Err.NumberCase 6' Display the error number.MessageBox.Show( Divided by zero )Case Else' Catch all other type of errors.MessageBox.Show(Err.Description)End Select'Resume execution to the line following the line that caused theerror.Resume NextEnd Sub Structured Error Handling With structured error handling, Visual Basic now has an effective way to prevent unexpectederrors from terminating the execution of the application. Structured error handling alsoprovides the programmers with a simpler way to create robust applications that are easier tomaintain.Structured error handling is implemented in Visual Basic. NET or Visual Basic 2005 with a Try...Catch...Finally block of statements. The Try...Catch...Finally block provides, for thefirst time to Visual Basic, the capability of nested error handling. Try...Catch...Finally Statements The following code demonstrates the structure of a Try...Catch...Finally statement. Try'Encapsulates a block of code that may produce a run-time error.Catch [Optional Filters]'The code runs if any of the statements in the Try block fails andfilter is evaluated as true.[Additional Catch Blocks]Finally'Code executed after Try and Catch statement.End Try The code that is expected to generate a run-time error should be placed in the Try block formonitoring by the error handler. If this code produces an error during execution, Visual Basicexamines all of the Catch statements implemented within the Try...Catch...Finally block tofind a condition that matches the error. If Visual Basic finds a matching condition, the controlof execution is transferred to the first line of code within the Catch statement. If Visual Basicdoes not find a matching condition, the error is propagated to the outer Try...Catch...Finally  statement. This statement can be located in the same procedure (nested statements) or in aprevious procedure that called the one that produced an error. This process is repeated until amatching statement is found. If a matching statement is not found, an error is produced, and  the application is terminated.The Finally statement is executed last, regardless of whether any errors were found. In otherwords, if no matching Catch statement is found, the Finally statement executes prior to thepropagation to the outer statements.This hierarchy and propagation are demonstrated with the following code: Module StructuredErrorSub Main()TryfnStructured()Catch ex As Exception ' Catches all exceptions.Debug.WriteLine( Exception Information: & vbCrLf & ex.ToString)'Displays the representation of current exception.FinallyDebug.WriteLine( Main: Finally executed ! )End TryEnd SubPublic Sub fnStructured()'Nested Error HandlingTryTryDim X As Integer = 9Dim Y As Integer = 0Dim Result As IntegerResult = X / YCatch e As DataException ' Catches only DataException.'Displays the representation of current exception.Debug.WriteLine( Exception Information: & vbCrLf & e.Message)FinallyDebug.WriteLine( fnStructured: Inner Finally executed ! )End TryCatch e As InvalidCastException ' Catches only defined exception.'Displays the representation of current exception.Debug.WriteLine( Exception Information: & vbCrLf & e.ToString)FinallyDebug.WriteLine( fnStructured: Outer Finally executed ! )End TryEnd SubEnd Module In the preceding example, an error is generated in a fnStructured() procedure. This is a Stack Overflow error, caused by division with a zero (0). This procedure implements two Try...Catch...Finally blocks of statements, but neither one has matching Catch statements,and the error is not caught. Before the control is propagated in the call stack, the code that isencapsulated in the Finally block is executed. The Try...Catch...Finally block that isimplemented in the Sub Main has a general condition that catches all exceptions that arethrown in its Try block.The following is the output of the preceding procedure: fnStructured: Inner Finally executed !fnStructured: Outer Finally executed !Exception Information:System.OverflowException: Arithmetic operation resulted in an overflow. atStructuredError.StructuredError.fnStructured() in C:\Documents andSettings\heikkiri\My Documents\Visual StudioProjects\Temp\StructuredError\StructuredError.vb:line 21 at
Related Search
We Need Your Support
Thank you for visiting our website and your interest in our free products and services. We are nonprofit website to share and download documents. To the running of this website, we need your help to support us.

Thanks to everyone for your continued support.

No, Thanks