November 26, 2014
Hot Topics:

The Book of Visual Studio .NET - Structured Exception Handling in VB

  • January 22, 2003
  • By Developer.com Staff
  • Send Email »
  • More Articles »
The Exit Try Statement

This example demonstrates the Exit Try statement. You could simply add the Exit Try statement to a previous example: however, go ahead and create a new button to keep each example separate for future reference.

1. Drag another button onto your Windows Form and label it "Exit Try".

2. Change the button name to "btnExitTry".

3. Cut and paste code from the Finally button to the Exit Try button.

4. In the Catch clause, place the "Exit Try" statement after the messageboxstatement:

Dim intResult as IntegerDim int1 as Integer = 5Dim int2 as Integer = 0TryintResult = int1 / int2Catch objException as System.OverflowExceptionMessagebox.Show("Divide by zero exception has occurred")Exit TryFinallyDim obj As New System.Text.StringBuilder()obj = obj.Append("Regardless of whether or not an ")obj = obj.Append("exception occurs, the Finally clause ")obj = obj.Append("will execute.")MessageBox.Show(obj.ToString)obj = NothingEnd Try

You will notice when the exception occurs, the exceptions message is displayed and the Try block is exited. In this case, the Finally block does not execute and is not a good place to clean up objects in memory.

Multiple Catch Statements

It is often preferable to use Multiple Catch statements in a single Try block, although the placement of Catch statements can impact performance. Once an exception is caught, the processing of the remaining Catch statements is aborted. Subsequently, once the Catch clause completes processing, the Finally clause is processed if available. To increase the performance of your Try blocks, place the most likely one to error or more common exceptions in the first Catch blocks while placing the least likely errors toward the end. Here's how to use Multiple Catch statements:

1. Drag another button onto your Windows Form and label it "Multiple Catch".

2. Change the button name to "btnMultipleCatch".

3. Cut and paste code from the Finally button to the Multiple Catch button.

4. Make the following changes as highlighted in the code below:

Dim intResult As IntegerDim int1 As Integer = 5Dim int2 As Integer = 0Dim str1 As StringTrystr1 = int1 / int2Throw (New Exception("A different exception"))Catch objException As System.OverflowExceptionMessageBox.Show("Divide by zero exception has occurred")CatchMessageBox.Show("Some other exception has occured.")FinallyDim obj As New System.Text.StringBuilder()obj = obj.Append("Regardless of whether or not an ")obj = obj.Append("exception occurs, the Finally clause ")obj = obj.Append("will execute.")MessageBox.Show(obj.ToString)obj = NothingEnd Try

As you step through the procedure you will notice that you no longerreceive an overflow exception. You will also notice that the string value receivingthe results of the calculation has the value "infinity" when dividing a number byzero. The overflow exception does not occur, however, when we threw an exceptionto the calling method. The first Catch clause is completely ignored, but thesecond Catch clause is not looking for any specific exception; as a result, the secondCatch clause catches all exceptions not already caught.

Historically, when you were building COM components, the best practice was to ensurethat all methods and components handled their own exceptions. The best practice with.NET components is to pass the exception to the client and allow the client to determinethe next course of action. This is due in part because all languages now understand howto deal with each other's languages exceptions, therefore, it is no longer critical for thelanguage catching the exception to also deal with the exception. Also, exceptions don'talways correlate to an error that occurred. Often an exception simply indicates anapplication state that is not what the method requires. This could be as simple as thedatabase is not available. In this care, no error has occurred in the code; however,because the database is unavailable, the method cannot complete its assigned task.

Getting Exception Information

The exception class has several properties and methods. You'll learn about a fewof the more notable ones here and then examine an example of each:

  • Source property: The Source property of the exception class is intended to hold the application or object name generating the exception. It can also be programmatically set, but if it is not set, the property returns the assembly name where the exception occurred.
  • Message property: The Message property is a string containing a description of the current exception.
  • TargetSite property: The TargetSite property is a string containing the name of the procedure where the exception occurred.
  • GetType method: The GetType method is inherited from the System.Object class and returns the type of exception that has occurred.
  • ToString method: The ToString method returns a string describing the current exception including information provided by several other exception class properties and methods.
Exception Class Properties and Methods Example

This example demonstrates the use of some exception class properties and methods:

1. Drag another button onto your Windows Form and label it "Properites/Methods."

2. Change the button name to "btnPropMeth."

3. Cut and paste code from the Finally button to the Properties/Methods button.

4. Add the following code to the newly pasted code:

Dim intResult as IntegerDim int1 as Integer = 5Dim int2 as Integer = 0TryintResult = int1 / int2Catch objException as System.OverflowExceptionMessagebox.Show("Divide by zero exception has occurred")'Source, Message, TargetSite, GetType, ToStringMessageBox.Show("Source: " & objException.Source())MessageBox.Show("Message: " &  objException.Message())MessageBox.Show("TargetSite: " & amp; objException.TargetSite.Name)MessageBox.Show("GetType.Name: " & amp; objException.GetType.Name)MessageBox.Show("ToString: " & amp; objException.ToString())FinallyDim obj As New System.Text.StringBuilder()obj = obj.Append("Regardless of whether or not an ")obj = obj.Append("exception occurs, the Finally clause ")obj = obj.Append("will execute.")MessageBox.Show(obj.ToString)obj = NothingEnd Try

This is the second of three parts of a sample chapter from The Book of Visual Studio .NET, ISBN 1-886411-69-7 from No Starch Press

# # #





Page 3 of 3



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Sitemap | Contact Us

Rocket Fuel