Handling Exceptions
Implement error handling in the UI: Raise and handle errors.
Implement error handling in the UI: Create and implement custom error messages.
Abruptly terminating the program when an exception occurs is not a good idea. Your application should be able to handle the exception and (if possible) recover from it. If recovery is not possible you can take other steps, such as notifying the user and then gracefully terminating the application.
The .NET Framework allows exception handling to interoperate among languages and across machines. You can throw an exception in code written in VB .NET and catch it in code written in C#, for example. In fact, the .NET framework also allows you to handle common exceptions thrown by legacy COM applications and legacy nonCOM Win32 applications.
Exception handling is such an integral part of .NET framework that when you look up a method in the product documentation, a section will always specify what exceptions a call to that method might throw.
You can handle exceptions in Visual Basic .NET programs by using a combination of the exception handling statements: Try, Catch, Finally, and Throw. In this section of the chapter I'll show how to use these statements.
The Try Block
You should place the code that can cause exception in a Try block. A typical Try block will look like this:
Try ' Code that may cause an exception End Try
You can place any valid Visual Basic .NET statements inside a Try block. That can include another Try block or a call to a method that places some of its statement inside a Try block. Thus at runtime you can have a hierarchy of Try blocks placed inside each other. When an exception occurs at any point, the CLR will search for the nearest Try block that encloses this code. The CLR will then pass control of the application to a matching Catch block (if any) and then to the Finally block associated with this Try block.
A Try block cannot exist on its own; it must be immediately followed by one or more Catch blocks or by a Finally block.
The Catch Block
You can have several Catch blocks immediately following a Try block. Each Catch block handles an exception of a particular type. When an exception occurs in a statement placed inside a Try block, the CLR looks for a matching Catch block capable of handling that type of exception. The formula that CLR uses to match the exception is simple. It will look for the first Catch block with either an exact match for the exception or for any of the exception's base classes. For example, a DivideByZeroException will match with any of these exceptions: DivideByZeroException, ArithmeticException, SystemException, and Exception (progressively more general classes from which DivideByZeroException is derived). In the case of multiple Catch blocks, only the first matching Catch block will be executed. All other Catch blocks will be ignored.
NOTE
Unhandled Exceptions If No Catch block matches a particular exception, that exception becomes an unhandled exception. The unhandled exception is propagated back to the code that called the current method. If the exception is not handled there, it will propagate further up the hierarchy of method calls. If the exception is not handled anywhere, it goes to the CLR for processing. The Common Language Runtime's default behavior is to terminate the program immediately.
When you write multiple Catch blocks, you must arrange them from specific exception types to more general exception types. For example, the Catch block for catching DivideByZeroException should always precede the Catch block for catching ArithmeticException because the DivideByZeroException derives from ArithmeticException and is therefore more specific. You'll get a compiler error if you do not follow this rule.
A Try block need not necessarily have a Catch block associated with it, but in that case it must have a Finally block associated with it. Step by Step 3.2 demonstrates the use of multiple Catch blocks to keep a program running gracefully despite errors.
STEP BY STEP 3.2 Handling Exceptions
-
Add a new Windows Form to your Visual Basic .NET project.
-
Create a form similar to the one in Step By Step 3.1 with the same names for controls (see Figure 3.1).
-
Add the following code to the Click event handler of btnCalculate:
Private Sub btnCalculate_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnCalculate.Click ' put all the code that may require graceful ' error recovery in a try block Try Dim decMiles As Decimal = _ Convert.ToDecimal(txtMiles.Text) Dim decGallons As Decimal = _ Convert.ToDecimal(txtGallons.Text) Dim decEfficiency As Decimal = decMiles / decGallons txtEfficiency.Text = _ String.Format("{0:n}", decEfficiency) ' each try block should at least ' have one catch or finally block ' catch blocks should be in order ' of specific to the generalized ' exceptions otherwise compilation ' generates an error Catch fe As FormatException Dim msg As String = String.Format( _ "Message: {0}\n Stack Trace:\n {1}", _ fe.Message, fe.StackTrace) MessageBox.Show(msg, fe.GetType().ToString()) Catch dbze As DivideByZeroException Dim msg As String = String.Format( _ "Message: {0}\n Stack Trace:\n {1}", _ dbze.Message, dbze.StackTrace) MessageBox.Show(msg, dbze.GetType().ToString()) ' catches all CLS-compliant exceptions Catch ex As Exception Dim msg As String = String.Format( _ "Message: {0}\n Stack Trace:\n {1}", _ ex.Message, ex.StackTrace) MessageBox.Show(msg, ex.GetType().ToString()) ' catches all other exception including ' non-CLS-compliant exceptions Catch ' just rethrow the exception to the caller Throw End Try
End Sub
-
Set the form as the startup object for the project.
-
Run the project. Enter values for miles and gallons and click the Calculate button to calculate the mileage efficiency as expected. Now enter the value zero in the gallons control and run the program. You will see that instead of abruptly terminating the program (as in the earlier example), the program shows a message about a DivideByZeroException (see Figure 3.4). After you dismiss the message, the program will continue running. Now enter some alphabetic characters in the fields instead of numbers and hit the calculate button again. This time you'll get a FormatException message and the program will continue to run. Now try entering a very large value for both the fields. If the values are large enough, the program will encounter an OverflowException, but since the program is catching all types of exceptions it will continue running.
Figure 3.4 DivideByZeroException.
The program in Step By Step 3.2 displays a message box when an exception occurs. The StackTrace property lists the methods that led up to the exception in the reverse order of their calling sequence to help you understand the flow of logic of the program. In a real application, you might choose to try to automatically fix the exceptions as well.
TIP
CLS- and Non-CLSCompliant Exceptions All languages that follow the Common Language Specification (CLS) throw exceptions whose type is or derives from System.Exception. A non-CLScompliant language might throw exceptions of other types as well. You can catch those types of exceptions by placing a general Catch block (one that does not specify any exception) within a Try block. In fact, a general Catch block can catch exceptions of all types, so it is most generic of all Catch blocks. This means that it should be the last Catch block among the multiple Catch blocks associated with a Try block.
When you write a Catch block to catch exceptions of the general Exception type, it will catch all CLS-compliant exceptions. That includes all exceptions unless you're interacting with legacy COM or Win32 API code. If you want to catch all exceptions, CLS-compliant or not, you can use a Catch block with no specific type. This Catch block must be last in the list of Catch blocks because it is the most generic.
If you are thinking that it's a good idea to catch all sorts of exceptions in your code and suppress them as soon as possible, think again. A good programmer will only catch an exception in code if the answer is yes to one or more of these questions:
Will I attempt to recover from this error in the Catch block?
Will I log the exception information in system event log or any other log file?
Will I add relevant information to the exception and rethrow it?
Will I execute cleanup code that must run even if an exception occurs?
If you answered no to all those questions, you should not catch the exception but rather just let it go. In that case, the exception will propagate up to the code that is calling your code. Possibly that code will have a better idea of what to do with the exception.
The Throw Statement
A Throw statement explicitly generates an exception in your code. You can use Throw to handle execution paths that lead to undesired results.
You should not throw an exception for anticipated cases, such as the user entering an invalid username or password. This occurrence can be handled in a method that returns a value indicating whether the logon was successful. If you don't have enough permissions to read records from the user table, that's a better candidate to raise an exception because a method to validate users should normally have read access to the user table.
Using exceptions to control the normal flow of execution is bad for two reasons:
It can make your code difficult to read and maintain because using Try and Catch blocks to deal with exceptions forces you to separate the regular program logic between separate locations.
It can make your programs slower because exception handling consumes more resources than just returning values from a method.
You can use the Throw statement in two ways. In its simplest form, you can just rethrow an exception that you've caught in a Catch block:
Catch ex As Exception ' TODO: Add code to write to the event log Throw
This usage of the Throw statement rethrows the exception that was just caught. It can be useful when you don't want to handle the exception yourself but want to take other actions (such as recording the error in an event log or sending an email notification about the error) when the exception occurs. Then you can pass the exception unchanged to the next method in the calling chain.
TIP
Custom Error Messages When creating an exception class, you should use the constructor that allows you to associate a custom error message with the exception instead of using the default constructor. The custom error message can pass specific information about the cause of the error and a possible way to resolve it.
The second way to use a Throw statement is to throw explicitly created exceptions. For example, this code creates and throws an exception:
Dim strMessage As String = _ "EndDate should be greater than the StartDate" Dim exNew As ArgumentOutOfRangeException = _ New ArgumentOutOfRangeException(strMessage) Throw exNew
In this example I first created a new instance of the Exception object and associated a custom error message with it Then I threw the newly created exception.
You are not required to put this usage of the Throw statement inside a Catch block because you're just creating and throwing a new exception rather than rethrowing an existing one. You will typically use this technique in raising your own custom exceptions. I'll show how to do that later in this chapter.
An alternate way to throw an exception is to throw it after wrapping it with additional useful information, for example:
Catch ane As ArgumentNullException ' TODO: Add code to create an entry in the log file Dim strMessage As String = "CustomerID cannot be null" Dim aneNew As ArgumentNullException = _ New ArgumentNullException(strMessage) Throw aneNew
You might need to catch an exception that you cannot handle completely. You would then perform any required processing and throw a more relevant and informative exception to the calling code, so that it can perform the rest of the processing. In this case, you can create a new exception whose constructor wraps the previously caught exception in the new exception's InnerException property. The calling code will now have more information available to handle the exception appropriately.
Because InnerException is also an exception, it might also store an exception object in its InnerException property, so what you are propagating is a chain of exceptions. This information can be very valuable at debugging time because it allows you to trace the problem to its origin.
The Finally Block
The Finally block contains the code that always executes whether any exception occurred. You can use the Finally block to write cleanup code to maintain your application in a consistent state and preserve the external environment. As an example you can write code to close files, database connections, or related I/O resources in a Finally block.
TIP
No Code in Between Try, Catch, and Finally Blocks When you write Try, Catch, and Finally blocks, they must be in immediate succession. You cannot write any code between the blocks, although you can place comments between them.
It is not necessary for a Try block to have an associated Finally block. However, if you do write a Finally block, you cannot have more than one, and the Finally block must appear after all the Catch blocks.
Step By Step 3.3 illustrates the use of the Finally block.
STEP BY STEP 3.3 Using a Finally Block
Add a new Windows Form to your Visual Basic .NET project.
-
Place two TextBox controls (txtFileName and txtText), two Label controls, and a Button control (btnSave) on the form's surface and arrange them as shown in Figure 3.5.
Figure 3.5 An application to test a Finally block.
-
Double-click the Button control to open the form's module. Enter a reference at the top of the module:
Imports System.IO
-
Enter this code to handle the Button's Click event:
Private Sub btnSave_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnSave.Click ' A StreamWriter writes characters to a stream Dim sw As StreamWriter Try sw = New StreamWriter(txtFilename.Text) ' Attempt to write the textbox contents in a file Dim strLine As String For Each strLine In txtText.Lines sw.WriteLine(strLine) Next ' This line only executes if ' there were no exceptions so far MessageBox.Show( _ "Contents written, without any exceptions") ' Catches all CLS-complaint exceptions Catch ex As Exception Dim msg As String = String.Format( _ "Message: {0}\n Stack Trace:\n {1}", _ ex.Message, ex.StackTrace) MessageBox.Show(msg, ex.GetType().ToString()) GoTo endit ' The finally block is always ' executed to make sure that the ' resources get closed whether or ' not an exception occurs. ' Even if there is a goto statement ' in catch or try block the ' final block is first executed before ' the control goes to the label Finally If Not sw Is Nothing Then sw.Close() End If MessageBox.Show( _ "Finally block always executes " & _ "whether or not exception occurs") End Try EndIt: MessageBox.Show("Control is at label: end")
End Sub
-
Set the form as the startup object for the project.
-
Run the project. Enter a file name and some text. Watch the order of the messages and note that the message box from the Finally block will always be displayed prior to the message box from the end label.
TIP
Finally Block Always Executes If you have a Finally block associated with a Try block, the code in the Finally block will always execute, regardless of whether an exception occurs.
Step By Step 3.3 illustrates that the Finally block always executes, even if a transfer of control statement, such as GoTo, is within a Try or Catch block. The compiler will not allow a transfer of control statement within a Finally block.
NOTE
Throwing Exceptions from a Finally Block Although throwing exceptions from a Finally block is perfectly legitimate, you should avoid doing so. A Finally block there might already have an unhandled exception waiting to be handled.
The Finally statement can be used in a Try block with no Catch block. For example:
Try ' Write code to allocate some resources Finally ' Write code to Dispose all allocated resources End Try
This usage ensures that allocated resources are properly disposed of no matter what happens in the Try block.
An exception occurs when a program encounters any unexpected problem during normal execution.
The Framework Class Library (FCL) provides two main types of exceptions: SystemException and ApplicationException. A SystemException represents an exception thrown by the Common Language Runtime while an ApplicationException represents an exception thrown by the your own code.
The System.Exception class is the base class for all CLS-compliant exceptions and provides the common functionality for exception handling.
A Try block consists of code that might raise an exception. A Try block cannot exist on its own but should be immediately followed by one or more Catch blocks or a Finally block.
The Catch block handles any exception raised by the code in the Try block. The runtime looks for a matching Catch block to handle the exception and uses the first Catch block with either the exact same exception or any of the exception's base classes.
If multiple Catch blocks are associated with a Try block, then the Catch blocks should be arranged in order from specific to general exception types.
The Throw statement is used to raise an exception.
The Finally block is used to enclose any code that needs to be run irrespective of whether an exception is raised.