Page OptionsLife Without On Error Goto StatementsDeborah KurataInStep Technologies, IncJuly 11, 2003Summary: In previous versions of Visual Basic, the best practice for handling errors was put On Error Goto in every routine, but there is no On Error statement in Visual Basic .NET. This Article Describes How To Use New Visual Basic .Net Features To Handle Errors WITHOUT Using ON Error Goto Statements. (8 Printed Pages) Overview: In the old version of Visual Basic, the best way to detect errors is set in each program ON Error Goto statement, but this statement in VB.NET is no longer available. This article is to tell how to handle errors outside the VB.NET through ON Error Goto. (8 pages) Introduction Introduction This is the second in a series of articles that describe the fundamental changes in Visual Basic® and how to do today with Visual Basic .Net what you used to do in prior versions of Visual Basic. The first article Covered Life without Control Arrays. This Article Looks athrow to usteout Using on Error Goto Statements. This is the second time in a series of articles, if you have passed a VB programmer, transition to VB. What kind of basic transformation needs to be experienced after NET. The First Article Covered Life without Control Arrays. This time I want to talk about how to use the method other than ORROR GOTO to handle the program error. There Are Three Types of Errors That Can Occur In Your Application: There are three errors in your program.
1.Anticipated errors: These are errors that your application can anticipate, such as attempting to read a file that does not exist or attempting to open a connection with an invalid connection string.2.Unanticipated errors: These are errors that occur in your application due to unexpected conditions, such as a programming or data error 3.Business rule violations:. These could be data entry errors, such as the user entering alpha characters into a numeric field, or they could be more complex business logic issues, such as Attempting to Delete An ORDER LINE ITEM for an ORDER That Has Already Been Shipped. 1, you can predict: This error is often presented, such as trying to open a file that does not exist, or trying to open a use invalid Connection String connection. 2, unpredictable misses me: This error occurs under conditions that cannot be foreseen, such as the error of the program and data. 3, violation of business specifications: This type may be an error in data entry, just like a value of a greek character into a numeric field; or, the mistakes have violated certain guidelines on the business, trying to try Go to delete an order already shipped. The original versions of Visual Basic provided On Error Goto for catching and handling of any errors in your application. For anticipated errors, the On Error Goto could catch the error and then your code could attempt to recover. For unanticipated errors, the On Error Goto could catch the error and then your code could terminate gracefully, without the user seeing a system error message. For business rule violations, your code could raise a specific error number and then the On error Goto statement could catch the error and display a user- Friendly Message. The old version of VB uses all errors in the ON Error Goto. For errors that can predict, ON ERROR GOTO captures the error after modifying the code. For errors that cannot be predicted, the ON Error Goto captures your code to continue execution. But for a violation of business specifications, On Error Goto can't capture well and may also return a friendly interface after it causes huge errors.
However, On Error Goto had some limits. Its goto style syntax made your routines structurally complex. And if you did not remember to exit the routine before the error handling at the bottom, it was easy to accidentally fall through the code into the error handling ......................................................................................................... But using a GOTO statement often makes your program complicated, if You have forgotten the final export in the program, which will cause the process to run unexpectedly. At this time, it is difficult to remove all the wrong code. (At least the error is going to happen) Visual Basic .NET HAS A RICH SET OF FEATURES THAT HAS A RICH SET OF FEATURES THAT HAS A RICH SET OF FEATURES THAT HAS A RICH SETOFERES OF IN ERROR GOTO, WITHOUT THE LIMITATIONS. VB.NET provides a rich support for the on Error Goto, excluded His limitations. Note Actually, Visual Basic .NET does support On Error Goto through the Microsoft Visual Basic .NET Compatibility library. This library allows you to retain some of the Visual Basic 6.0 features in Visual Basic .NET to simplify the migration process. Features of this library SHOULD BE Used Only for Migration. Remind: In fact, VB.NET's MSVB.NET compatibility does not support On Error Goto, this compatibility library is mainly characteristic of some VB6, making it easier to transplant to VB.NET. This object library is for transplantation. Catching Exceptions catch exceptions In .NET terms, errors are no longer called errors, but rather exceptions. Anticipated errors, unanticipated errors, and business rule violations are all considered to be exceptions. .Net term, the "error" is generally referred to For "abnormal", whether it is a foreseeable error, unforeseen mistakes, violation of business processes, is called exception.
After writing any routine, it is always a good idea to think about the exceptions that the routine could cause (anticipated errors), any unexpected exceptions that the routine could generate (unanticipated errors), and any business rules that the routine could violate. When After the procedure is completed, it should develop good habits, think about the error (ie, foresee errors), which cannot be estimated (unforeseen errors) or to identify the procedure of business requirements section. For example, many applications use a login form or page to control access to the application and its functions The code to validate the login is executed when the user clicks on the login button as follows:. For example, many programs will use a login window to get User information To control software open features, login processes trigger as follows when the user presses the [Login] button: Private Sub Cmdlogin_Click (Byval E AS Object, _ Byval E ASTEM.EventArgs) Handles Cmdlogin.Click Dim Ouser AS User ) Dim bValid as Boolean oUser = New User () bValid = oUser.ValidateLogin (txtUserName.Text, txtPassword.Text) If bValid then DialogResult = DialogResult.OK End If oUser.Dispose oUser = NothingEnd SubThis code creates a new instance of the User class and then calls its ValidateLogin method to access the database and validate the user-entered username and password. If the login is valid, it sets DialogResult to OK to close the login form. It then disposes of the User class instance and returns. Code Create a User class entity and call the ValidateLogin method to connect to the database to verify the identity of the user. If the user is legal, the "OK" is attached to DialogResult and clear the User class and its entity finally returns.
There are several places in this code that an exception could occur. The line of code that creates the new instance from the User class could generate an unanticipated exception if the instance can not be created for some reason. The ValidateLogin method could generate anticipated exceptions (such AS An Invalid Connection String), Unanticipated Exceptions (Such As a Missing Table Field or Stored Pro), or Business Rule Violations (SUCH AS PASSING AN Empty User Name). This code will produce some exceptions. If the User class entity cannot be created for some accident reasons. The ValidateLogin method can also produce a foreseeable error (such as the failure of database connections), and unforeseen errors (computers can't find corresponding fields and stored procedures), and even business process errors (users entered an empty username) INSTEAD of adding an On Error Goto to catch these exceptions, the exceptions can be caught using a .NET Try / Catch block The Try / Catch syntax makes it easier to catch and process exceptions in a structured manner;. hence the reason that .NET exception Handling is offen referred to as structured exception handling (seh). Use the TRY / CATCH module in .NET instead of the on Error Goto to capture these exceptions. Try / catch can be more easily captured and abnormal through a structure; therefore, .NET usually uses an abnormality (SEH) to process an exception.
A Try / Catch block could be added to the code as follows: a Try / Catch module can be added to the code: Private Sub cmdLogin_Click (ByVal sender As Object, _ ByVal e As System.EventArgs) Handles cmdLogin.Click Dim oUser As User () Dim bValid as Boolean Try oUser = New User () bValid = oUser.ValidateLogin (txtUserName.Text, txtPassword.Text) If bValid then DialogResult = DialogResult.OK End If oUser.Dispose oUser = Nothing Catch ex As Exception MessageBox.Show (ex.Message) End TryEnd subIf any exception occurs in the Try block, the Catch block picks up the exception and the code within the Catch block will execute. in this case, the catch will grab any exception, assign the exception to the ex Variable, And Display a Message Box Containing The Exception Message. If No Exception Occurs, The Catch Block Code Is Ignored. If an exception occurs in the TRY module, the catch module can and extract an exception and perform the code behind the catch. In this example, the CATCH module can extract an abnormality and attach an exception to an EX variable, which displays a message containing the error content. If there is no abnormality, the Catch module will be slightly passed. If you look closely at the example above, you will notice that the code to dispose of the instance will not be executed if an exception occurs. To correct this, the code could be repeated in the Catch block, but that means duplicating code. A better approach, be to use, the optink, if you carefully look at the code above, you will find that if an abnormality occurs, the entity clearance operation will not happen. To solve this problem, clear the code of the entity is also added to the CATCH module, which will cause a duplicate code.
Private Sub cmdLogin_Click (ByVal sender As Object, _ ByVal e As System.EventArgs) Handles cmdLogin.Click Dim oUser As User () Dim bValid as Boolean Try oUser = New User () bValid = oUser.ValidateLogin (txtUserName.Text, txtPassword. Text) If bValid then DialogResult = DialogResult.OK End If Catch ex As Exception MessageBox.Show (ex.Message) Finally oUser.Dispose () oUser = Nothing End TryEnd SubThe code in the Finally block will be executed after the Try block completes successfully , after the Catch block executes, or after any Return statements are executed in the Try or Catch blocks. Any code that needs to be executed before leaving the routine should be added to the Finally block. Notice how the declaration of the User object was done outside of the Try block. This is required if the object variable will be accessible both from the Try block and the Finally block because .NET after has block-scoped variables.Finally module, Catch Try executed after the module is successful, or Reture statement Start after the end. All transactions that need to be performed before the endprace can be added to the finally module. However, the User object is declared before the TRY module, which should be used as the module-level variable to be used in TRY and FINALLY. In prior version of Visual Basic, there were three types of variable scoping: in the early VB, there are three variables scope:. • Global-level variables were accessible to the entire application • Module-level variables were accessible in the Code File (Form, Class, or Module) in which they were scided. • The global variable is valid throughout the program. • The module-level variable is in the file where the code is located (form, class, module). • Local variables are only valid during their process.
In .NET, there is a fourth type of scoping-block-level scoping. Variables declared within a block, such as a Try block or For / Next block, are only accessible within the block.If the declaration of the User object had been inside of the Try block, the Finally block would not be able to reference the variable. So object variables that will need to be disposed in the Finally block must be declared outside of the Try block. in .Net, the fourth part of this . Variables are declared in the module, just like the TRY module and the FOR / NEXT module, the variable works in the module. If the User object is declared in the TRY module, then he will not be accessed in Finally. Therefore, the value of the object will be removed in the FINALLY module, apparently, it is necessary to be declared in the TRY module. Throwing Exceptions throw exception One of the reasons that exceptions are not called errors is that the term error frequently implies a coding mistake. An exception is any violation of a routine's implicit assumptions. The .NET Framework will throw exceptions to your application if your code violates any of the .NET Framework implicit assumptions. For example, the .NET Framework assumes that a divisor will be a non-zero number. If your code attempts to divide by 0, an exception will be thrown. You can then catch these exceptions Umophysical part is called one of the causes because the error is characterized, and it is often also included in an error. An exception is any hypothetical assumption that violates the program. As long as your code contains anything that violates the inherent hypothesis of the .NET framework, the .NET framework will throw out an exception. For example, the .NET framework is considered to be a value of a non-zero. If your code is trying to put 0 as a division, an exception will be thrown out. You can capture it in the TRY / CATHC module.
When writing your routines, you should follow the same guidelines and throw exceptions when any implicit assumption is violated. To throw an exception, use the Throw statement and throw a new instance of the appropriate exception class. (See the online help for the list of .NET exceptions that youcan throw.) For example, the ValidateLogin method makes the assumption that it should receive non-empty values as the parameters. If the values are empty, it should throw an ArgumentOutOfRange exception. when you write a program, you According to the principle of guidance, a variety of unusual assumptions are throwded out after violation of the system, and an exception class is throwded out using the throw statement. For example, the ValidateLogin event assumes that the parameter it receives will not have a null value. If the empty value appears, he will throw a ArgumentOutofRange.
Public Function ValidateLogin (ByVal sUserName As String, _ ByVal sPassword As String) As Boolean If sUserName.length = 0 OrElse sPassword.Length = 0 Then Throw New ArgumentOutOfRangeException ( "Username and password are required.") End If 'Code to validate login here Return TrueEnd FunctionThis Throw statement creates a new instance of the ArgumentOutOfRangeException and defines the message text. When this statement is executed, the exception is thrown. The code following the Throw statement is not executed, but rather the .NET runtime looks for a Try / Catch block. IF The Current Code Is Not in A Try Block, The .NET Runtime Looks Up The Call Stack To See et. an associated Catch block. If the .NET runtime finds an appropriate Try / Catch block, it executes the code in the Catch block. Otherwise, it displays the unhandled exception message and terminates the application. Note As the .NET runtime looks for associated Try blocks up the call stack, it will execute any code in the associated Finally block of the Try blocks before continuing up the call stack. This statement creates an abnormal ArgumentOutOfRangeException and defines a message when the statement Executed, the exception will throw out. The statement behind throw will not be executed, but .Net is automatically looking for the TRY / CATCH module when it is not in a TRY module. . If a TRY / CATCH module is found when .NET runtime, execute the code in the catch module. Otherwise, an error message is displayed and the program is terminated. Reminder: When the .NET is running from the stack, he will first perform all the code in the finally module corresponding to TRY before proceeding.
In addition to throwing .NET exceptions, you may find that you want to define your own custom exceptions. In the login example, in addition to throwing the ArgumentOutOfRangeException you may want to throw a custom exception if the username is not valid and a different custom Exception if the password is not valid. In addition, you can define a custom exception for the .NET. Take the login as an example, you can attach a custom anomalies outside the username and password other than ArgumentOutofrangeException. To create a custom exception, you can create your own exception class. To ensure that it behaves as a .NET exception, your new exception class should inherit from one of the .NET exception classes. The recommended class to use for your inheritance is the ApplicationException Class. For example, the usernamenotfoundexception Class Would Look Like this: To create a custom exception, you can customize an exception class. To ensure that it is an exception of .NET, your exception class should inherit from one .NET exception class. One of the better inheritance objects is the ApplicationException class. UsernameNotFoundException class as the following example: Public Class UsernameNotFoundException: Inherits ApplicationException Public Sub New () MyBase.New () End Sub Public Sub New (ByVal message As String) MyBase.New (message) End Sub Public Sub New (ByVal message As String, ByVal innerEx As Exception) MyBase.New (message, innerEx) End SubEnd ClassWhen using inheritance, the new class automatically has all of the properties and methods of the inherited class. So, the UsernameNotFoundException class has all of the standard ApplicationException properties , such as the message and call stack the new class does not inherit any of the constructors of the inherited class; hence the need for this class to have its own constructors the ApplicationException class supports three constructors:.. using inheritance when new The class will automatically inherit all the properties from the parent class.
Therefore, the USERNAMENOTFoundException class has all properties of the ApplicationException class, such as messages and calls. The new class does not inherit the parameter table of the parent class, so you need to define the parameter table for the new class. ApplicationException supports the following three parameter structures. • One with no parameters no parameters • One with just the message parameter is only one message parameter • One with both a message and an inner exception message and an inner exception The last constructor is used in the case when the code catches an exception and The last parameter structure is used for code intercepting an exception after the code is re-throwing an exception, but it wants to maintain the original exception information. You can also add custom properties and methods to your new exception class. For example, you could add a username property to your exception class so that you could log any exceptions and include the username of the user that had the exception.The routine can throw Custom Excetions As Follows: Similarly You can customize properties and events for your new exception, for example, you can add a username property for your exception to record all information that produces exceptions.
Defined by throw exception code is as follows: Public Function ValidateLogin (ByVal sUserName As String, _ ByVal sPassword As String) As Boolean If sUserName.length = 0 OrElse sPassword.Length = 0 Then Throw New ArgumentOutOfRangeException ( "Username and password are required." ) End If 'Code to locate the user record here If iUserRecordID = 0 Then Throw New UsernameNotFoundException ( "Invalid username") End If' Code to retrieve the password from the user record here If sPassword <> sUserRecordPassword Then Throw New PasswordInvalidException ( "Invalid password ") End If Return TrueEnd FunctionThis routine then throws either a .NET exception or a custom exception if any of the routine's implicit assumptions are violated. Notice that there is no Try / Catch block around this code. You will find that most of your Methods Won't need try / catch blocks. Rather, All of Your Event Procedure Code Will Be Your of Defense, Catching Any Exceptions Thrown by any of the methods called by Those Event P ROCEDURES. In this program, if any program error occurs, .NET's exception and custom exception will be thrown at the same time. Note that there is no TRY / CATCH module in the code above, and you will find that you don't need the TRY / CATCH module. That is to say, all your event programs are your protection line, and the way to be thrown by the event will be intercepted. Catching Custom Exceptions capture error The Try / Catch block code shown at the beginning of this article provided a generic exception handler using a generic exception filter-ex as Exception. This filter would catch any .NET exception or custom exception that inherited from a .NET Exception. in the login example, The Generic Exception Filter Would Correctly Catch Any Exception thrown from the validatelogin method. At the beginning of this article, we demonstrate a general exception provided by a general exception in the TRY / CATCH module. You can capture all .NET exceptions and inheritance .NET exception.
In the login example, this general exception parameter can correctly capture an exception thrown from the ValidateLogin event. There may be cases, however, when the code needs to perform different processes depending on which exception was thrown. A Try / Catch block can contain any number of Catch blocks with more explicit exception filters that can catch specific custom or .NET exceptions and perform Processing for Each Type of Exception. In some cases, a try / catch module can contain many Catch modules to add different parameters when performing different processing according to the content throwing exceptions. Handle various custom or .NET exceptions. Private Sub cmdLogin_Click (ByVal sender As Object, _ ByVal e As System.EventArgs) Handles cmdLogin.Click Dim oUser As User () Dim bValid as Boolean Try oUser = New User () bValid = oUser.ValidateLogin (txtUserName.Text, txtPassword. Text) If bValid then DialogResult = DialogResult.OK End If Catch ex As UsernameNotFoundException MessageBox.Show (ex.Message) txtUserName.Focus () Catch ex As PasswordInvalidException MessageBox.Show (ex.Message) txtPassword.Focus () Catch ex As Exception MessageBox.Show (ex.Message) Finally oUser.Dispose () oUser = Nothing End TryEnd SubThe order of these exception filters is important. The more specific filters should always be defined before the generic filters. The most generic filter (ex as Exception) The parameters of the exception IS caught. Exception is caught. Abnormal parameters are important, and some special parameters are usually defined before the general exception parameters. The general abnormal parameters are usually placed in the end so that the unpredictable exception can be intercepted.