- Sub Procedures
- Creating Functions
- Using Optional Arguments
- Passing a Variable Number of Arguments
- Preserving Data Between Procedure Calls
- Understanding Scope
- Handling Runtime Errors
- Unstructured Exception Handling
- Structured Exception Handling
- Introducing Classes and Objects
- Summary
- Q&A
- Workshop
Structured Exception Handling
In addition to unstructured exception handling, Visual Basic .NET also supports structured exception handling. It's important to know about structured exception handling because not only does it allow you to handle exceptions, but in some circumstances, Visual Basic will insist that you handle possible exceptions using structured exception handling before running your code.
In Visual Basic .NET, structured exception handling centers on the Try/Catch statement. In this statement, you put sensitive, exception-prone code in a Try block, and if an exception occurs, the code in the Try block will throw the exception (actually an exception object), which will then be caught by a following Catch block. The code in the Catch block handles the exception. Unlike unstructured exception handling, where exception handling can be spread throughout your code, structured exception handling all takes place inside a Try/Catch statement. Here's the syntax of that statement:
Try [ tryStatements ] [Catch [ exception1 [ As type1 ] ] [ When expression1 ] catchStatements1 [Exit Try] [Catch [ exception2 [ As type2 ] ] [When expression2 ] catchStatements2 [ Exit Try ] . . . [Catch [ exceptionn [ As typen ] ] [ When expressionn ] catchStatementsn ] [ Exit Try ] [ Finally [ finallyStatements ] ] End Try
The parts of this statement are as follows:
TryStarts the Try block.
tryStatementsSpecifies the sensitive statements where you anticipate possible exceptions.
CatchStarts the block that catches and handles the exception(s).
exceptionSpecifies a variable that you give to the exception.
typeIndicates the type of the exception you want to catch in a Catch block.
When expressionSpecifies a Catch block clause that means the Catch block will catch exceptions only when expression is True. The expression is an expression used to select exceptions to handle; it must be convertible to a Boolean value. It is often used to select errors by number.
catchStatementsSpecifies statements that handle exceptions occurring in the Try block.
Exit TryExits a Try/Catch statement immediately. Execution moves to the code immediately following the End Try statement.
FinallyStarts a Finally block that is always executed when execution leaves the Try/Catch statement. If a Try statement does not contain any Catch blocks, it must contain a Finally block. Exit Try is not allowed in Finally blocks.
finallyStatementsSpecifies statements that are executed after all other exception processing has occurred.
Here's an example, the Exception project in the code for this book, to get us started. In this case, the exception-prone code in the Try block executes a division by zero, which generates an overflow exception:
Module Module1 Sub Main() Dim intItem1 As Integer = 0 Dim intItem2 As Integer = 128 Dim intResult As Integer Try intResult = intItem2 / intItem1 Console.WriteLine("The answer is " & intResult) Console.WriteLine("Press Enter to continue...") Console.ReadLine() . . . End Sub End Module
When an exception occurs, control leaves the Try block and enters the Catch block, where you can handle the exception something like you see in Listing 3.8.
Listing 3.8 Using Structured Exception Handling (Exception project, Module1.vb)
Module Module1 Sub Main() Dim intItem1 As Integer = 0 Dim intItem2 As Integer = 128 Dim intResult As Integer Try intResult = intItem2 / intItem1 Console.WriteLine("The answer is " & intResult) Console.WriteLine("Press Enter to continue...") Console.ReadLine() Catch Console.WriteLine("An overflow exception occurred.") Console.WriteLine("Press Enter to continue...") Console.ReadLine() End Try End Sub End Module
When you run this application, you'll see this result:
An overflow exception occurred. Press Enter to continue...
You can also get Visual Basic's error message for an exception. To do that, you can create a variable, called e here, which will hold the exception:
Try intResult = intItem2 / intItem1 . . . Catch e As Exception Console.WriteLine("An overflow exception occurred.") Console.WriteLine("Press Enter to continue...") Console.ReadLine() End Try
Now that you have the actual Visual Basic exception object corresponding to the exception that occurred in the variable named e, you can use e.ToString to display the exception as text like this:
Try intResult = intItem2 / intItem1 . . . Catch e As Exception Console.WriteLine(e.ToString()) Console.WriteLine("Press Enter to continue...") Console.ReadLine() End Try
Here's what you might see when a division by zero takes place:
System.OverflowException: Arithmetic operation resulted in an overflow. at Filters.Module1.Main() in C:\vbnet 2003\Day3\Filters\Module1.vb:line 7 Press Enter to continue...
Although this result is good for programmers because it indicates the location of the problem, this exception description isn't very helpful to users. Instead, you can use the exception object's Message property to display a better error message:
Try intResult = intItem2 / intItem1 . . . Catch e As Exception Console.WriteLine(e.Message) Console.WriteLine("Press Enter to continue...") Console.ReadLine() End Try
Here's what you'll see in this case:
Arithmetic operation resulted in an overflow. Press Enter to continue...
The generic Catch e As Exception block in this example catches all types of exceptions, but, as with unstructured exception handling, you can narrow down an exception handler to catching only a single type of exception, a process called filtering.
Exception Filtering in the Catch Block
A Catch e As Exception block catches all types of exceptions and stores the exception object in a variable named e. However, you can specify that a Catch block catch only certain types of exceptions with the As type clause. (Table 3.1 contains a list of some of the Visual Basic .NET exception types.) For example, to catch only exceptions of the type OverflowException, you can add a Catch block as in Listing 3.9.
Listing 3.9 Filtered Exception Handling (Filters project, Module1.vb)
Module Module1 Sub Main() Dim intItem1 As Integer = 0 Dim intItem2 As Integer = 128 Dim intResult As Integer Try intResult = intItem2 / intItem1 Console.WriteLine("The answer is " & intResult) Console.WriteLine("Press Enter to continue...") Console.ReadLine() Catch e As OverflowException Console.WriteLine("An overflow exception occurred.") Console.WriteLine("Press Enter to continue...") Console.ReadLine() End Try End Sub End Module
TIP
If you want to get the name of an exception and you're able to cause that exception while testing your program, call e.getType() to get the type of the exception as a string. When you know the name of the exception, you can provide a Catch block for it.
You can also use a When clause in a Catch block to further filter exception handling. For example, your code may have multiple sections that may cause overflows, and you want to handle the overflows only when intItem1 is 0 in a particular Catch block. You can do that in a When clause that uses the logical expression intItem1 = 0:
Try intResult = intItem2 / intItem1 . . . Catch e As OverflowException When intItem1 = 0 Console.WriteLine("An overflow exception occurred.") Console.WriteLine("Press Enter to continue...") Console.ReadLine() End Try
You can also filter on error numbers like this:
Try intResult = intItem2 / intItem1 . . . Catch e As OverflowException When Err.Number = 6 Console.WriteLine("An overflow exception occurred.") Console.WriteLine("Press Enter to continue...") Console.ReadLine() End Try
But what about handling the other overflow exceptions caused by your code. Can you have multiple Catch blocks in the same Try/Catch statement? You certainly can.
Using Multiple Catch Statements
If you want to handle a number of different exceptions, you can use multiple Catch blocks. In the following example, different Catch blocks handle overflow exceptions, out-of-memory exceptions, and array index out-of-range exceptions (which occur when an array index has been set to a negative value or to a value greater than the upper bound of the array):
Module Module1 Sub Main() Dim intItem1 As Integer = 0 Dim intItem2 As Integer = 128 Dim intResult As Integer Try intResult = intItem2 / intItem1 Console.WriteLine("The answer is " & intResult) Console.WriteLine("Press Enter to continue...") Console.ReadLine() Catch e As OverflowException Console.WriteLine("An overflow exception occurred.") Console.WriteLine("Press Enter to continue...") Console.ReadLine() Catch e As OutOfMemoryException Console.WriteLine("Out of memory.") Console.WriteLine("Press Enter to continue...") Console.ReadLine() Catch e As IndexOutOfRangeException Console.WriteLine("Array index out of range.") Console.WriteLine("Press Enter to continue...") Console.ReadLine() End Try End Sub End Module
Using multiple Catch blocks like this gives you a good handle on handling exceptions of various types. Each Catch block serves as a different exception handler, and you can place exception-specific code in each such block.
Using Finally
Another part of the Try/Catch statement that you should know about is the Finally block. The code in the Finally block, if there is one, is always executed in a Try/Catch statement, even if there was no exception, and even if you execute an Exit Try statement. This allows you to make sure that even if there was an exception you'll be sure of running this code (as long as the whole program is still running). Listing 3.10 shows an example with a Finally block, the Finally example in the code for the book.
Listing 3.10 Using the Finally Statement (Finally project, Module1.vb)
Module Module1 Sub Main() Dim intItem1 As Integer = 0 Dim intItem2 As Integer = 128 Dim intResult As Integer Try intResult = intItem2 / intItem1 Console.WriteLine("The answer is " & intResult) Catch e As OverflowException Console.WriteLine("An overflow exception occurred.") Catch e As OutOfMemoryException Console.WriteLine("Out of memory.") Catch e As IndexOutOfRangeException Console.WriteLine("Array index out of range.") Finally Console.WriteLine("Press Enter to continue...") Console.ReadLine() End Try End Sub End Module
In this case, you'll always see the "Press Enter to continue..." prompt, and the code will wait for you to press Enter whether or not an exception was thrown. Here's what you might see:
An overflow exception occurred. Press Enter to continue...
Throwing an Exception Yourself
You can throw an exception yourself in your code by using the Throw statement. In this example the code explicitly throws an overflow exception:
Module Module1 Sub Main() Try Throw New OverflowException() Console.WriteLine("Press Enter to continue...") Console.ReadLine() Catch e As Exception Console.WriteLine(e.Message) Console.WriteLine("Press Enter to continue...") Console.ReadLine() End Try End Sub End Module
Throwing your own exceptions like this gives you a great deal of control over the exception-handling process. And you're not limited to just the exceptions that Visual Basic has already defined either, as we'll see next.
Creating and Throwing Custom Exceptions
You can, in fact, customize and create your own exceptions. To do that, you throw an exception using the ApplicationException object. Listing 3.11 shows an example, the CustomException example in the code for this book, where we're creating a custom exception and giving it the text "This is a new exception".
Listing 3.11 Creating Custom Exceptions (CustomException project, Module1.vb)
Module Module1 Sub Main() Try Throw New ApplicationException("You threw this custom exception.") Catch e As Exception Console.WriteLine(e.Message) Finally Console.WriteLine("Press Enter to continue...") Console.ReadLine() End Try End Sub End Module
Here's what you see when you run this application:
You threw this custom exception. Press Enter to continue...
Note the New keyword in the statement Throw New ApplicationException("You threw this custom exception."). You use this keyword when you create new objects.
As we head into tomorrow's work with Windows forms, which will take us through five days, we'll need to know something about classes and objects. For that reason, we'll get a good introduction to them here.