Handling Exceptions
Implement error handling in the user interface:
Create and implement custom error messages.
Raise and handle errors.
Abruptly terminating a program when an exception occurs is not a good idea. An application should be able to handle an exception and, if possible, try to recover from it. If recovery is not possible, you can have the program take other steps, such as notify the user and then gracefully terminate the application.
TIP
Floating-Point Types and Exceptions Operations that involve floating-point types never produce exceptions. Instead, in exceptional situations, floating-point operations are evaluated by using the following rules:
If the result of a floating-point operation is too small for the destination format, the result of the operation becomes positive zero or negative zero.
If the result of a floating-point operation is too large for the destination format, the result of the operation becomes positive infinity or negative infinity.
If a floating-point operation is invalid, the result of the operation becomes NaN (not a number).
The .NET Framework allows exception handling to interoperate among languages and across machines. You can catch exceptions thrown by code written in one .NET language in a different .NET language. The .NET framework also allows you to handle exceptions thrown by legacy Component Object Model (COM) applications and legacy non-COM Windows applications.
Exception handling is such an integral part of the .NET framework that when you look for a method reference in the product documentation, there is always a section that specifies what exceptions a call to that method might throw.
You can handle exceptions in Visual C# .NET programs by using a combination of exception handling statements: try, catch, finally, and throw.
The try Block
You should place the code that might cause exceptions in a try block. A typical try block looks like this:
try { //code that may cause exception }
You can place any valid C# statements inside a try block, including another try block or a call to a method that places some of its statements inside a try block. The point is, at runtime you may have a hierarchy of try blocks placed inside each other. When an exception occurs at any point, rather than executing any further lines of code, the CLR searches for the nearest try block that encloses this code. The control is then passed 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 either one or more catch blocks or 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 the try block, the CLR looks for a matching catch block that is capable of handling that type of exception. A typical try-catch block looks like this:
try { //code that may cause exception } catch(ExceptionTypeA) { //Statements to handle errors occurring //in the associated try block } catch(ExceptionTypeB) { //Statements to handle errors occurring //in the associated try block }
The formula the CLR uses to match the exception is simple: While matching it looks for the first catch block with either the exact same exception or any of the exception's base classes. For example, a DivideByZeroException exception would match any of these exceptions: DivideByZeroException, ArithmeticException, SystemException, and Exception. In the case of multiple catch blocks, only the first matching catch block is executed. All other catch blocks are ignored.
When you write multiple catch blocks, you need to arrange them from specific exception types to more general exception types. For example, the catch block for catching a DivideByZeroException exception should always precede the catch block for catching a ArithmeticException exception. This is because the DivideByZeroException exception derives from ArithmeticException and is therefore more specific than the latter. The compiler flags an error if you do not follow this rule.
NOTE
Exception Handling Hierarchy If there is no matching catch block, an unhandled exception results. The unhandled exception is propagated back to its caller code. If the exception is not handled there, it propagates further up the hierarchy of method calls. If the exception is not handled anywhere, it goes to the CLR, whose default behavior is to terminate the program immediately.
A try block need not necessarily have a catch block associated with it, but if it does not, it must have a finally block associated with it.
STEP BY STEP 3.2 - Handling Exceptions
-
Add a new Windows form to the project. Name it StepByStep3_2.
-
Create a form similar to the one created in Step by Step 3.1 (refer to Figure 3.1), with the same names for the controls.
-
Add the following code to the Click event handler of btnCalculate:
private void btnCalculate_Click( object sender, System.EventArgs e) { //put all the code that may require graceful //error recovery in a try block try { decimal decMiles = Convert.ToDecimal(txtMiles.Text); decimal decGallons = Convert.ToDecimal(txtGallons.Text); decimal decEfficiency = decMiles/decGallons; txtEfficiency.Text = String.Format("{0:n}", decEfficiency); } // try block should at least have one catch or a // finally block. catch block should be in order // of specific to the generalized exceptions // otherwise compilation generates an error catch (FormatException fe) { string msg = String.Format( "Message: {0}\n Stack Trace:\n {1}", fe.Message, fe.StackTrace); MessageBox.Show(msg, fe.GetType().ToString()); } catch (DivideByZeroException dbze) { string msg = 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(Exception ex) { string msg = String.Format( "Message: {0}\n Stack Trace:\n {1}", ex.Message, ex.StackTrace); MessageBox.Show(msg, ex.GetType().ToString()); } //catches all other exceptions including //the NON-CLS compliant exceptions catch { //just rethrow the exception to the caller throw; }
}
TIP
CLS- and Non-CLS-Compliant Exceptions All languages that follow the Common Language Specification (CLS) throw exceptions of type System.Exception or a type that derives from System.Exception. A non-CLS-compliant language may throw exceptions of other types, too. You can catch those types of exceptions by placing a general catch block (that does not specify any exception) with a try block. In fact, a general catch block can catch exceptions of all types, so it is the most generic of all catch blocks and should be the last catch block among the multiple catch blocks associated with a try block.
-
Insert the Main() method to launch the form. Set the form as the startup object for the project.
-
Run the project. Enter values for miles and gallons and click the Calculate button. The program calculates the mileage efficiency, as expected. Now enter the value 0 in the Gallons of gas used field and run the program. Instead of abruptly terminating as in the earlier case, the program shows a message about the DivideByZeroException exception, as shown in Figure 3.4, and it continues running. Now enter some alphabetic characters instead of number in the fields and click the Calculate button. This time you get a FormatException exception, and the program continues to run. Now try entering very large values in both the fields. If the values are large enough, the program encounters an OverflowException exception, but because the program is catching all types of exceptions, it continues running.
Figure 3.4 To get information about an exception, you can catch the Exception object and access its Message property.
NOTE
checked and unchecked Visual C# .NET provides the checked and unchecked keywords, which can be used to enclose a block of statements (for example, checked {a = c/d}) or as an operator when you supply parameters enclosed in parentheses (for example, unchecked(c/d)). The checked keyword enforces checking of any arithmetic operation for overflow exceptions. If constant values are involved, they are checked for overflow at compile time. The unchecked keyword suppresses the overflow checking and instead of raising an OverflowException exception, the unchecked keyword returns a truncated value in case of overflow.
If checked and unchecked are not used, the default behavior in C# is to raise an exception in case of overflow for a constant expression or truncate the results in case of overflow for the nonconstant expressions.
The program in Step by Step 3.2 displays a message box when an exception occurs; the StackTrace property lists the methods in the reverse order of their calling sequence. This helps you understand the logical flow of the program. You can also place any appropriate error handling code in place, and you can display a message box.
When you write a catch block that catches exceptions of type Exception, the program catches all CLS-compliant exceptions. This includes all exceptions, unless you are interacting with legacy COM or Windows 32-bit Application Programming Interface (Win32 API) code. If you want to catch all kinds of exceptions, whether CLS-compliant or not, you can place a catch block with no specific type. A catch block like this must be the last catch block in the list of catch blocks because it is the most generic one.
NOTE
Do Not Use Exceptions to Control the Normal Flow of Execution Using exceptions to control the normal flow of execution can make your code difficult to read and maintain because the use of try-catch blocks to deal with exceptions forces you to fork the regular program logic between two separate locationsthe try block and the catch block.
You might be thinking that it is a good idea to catch all sorts of exceptions in your code and suppress them as soon as possible. But it is not a good idea. A good programmer catches an exception in code only if he or she can answer yes to one or more of the following questions:
Will I attempt to recover from this error in the catch block?
Will I log the exception information in the system event log or another 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 answer no to all these questions, then you should not catch the exception but rather just let it go. In that case, the exception propagates up to the calling code, and the calling code might have a better idea of how to handle the exception.
The throw Statement
A throw statement explicitly generates an exception in code. You use throw when a particular path in code results in an anomalous situation.
You should not throw exceptions for anticipated cases such as the user entering an invalid username or password; instead, you can handle this in a method that returns a value indicating whether the login is successful. If you do not have the correct permissions to read records from the user table and you try to read those records, an exception is likely to occur because a method for validating users should normally have read access to the user table.
WARNING
Use throw Only When Required The throw statement is an expensive operation. Use of throw consumes significant system resources compared to just returning a value from a method. You should use the throw statement cautiously and only when necessary because it has the potential to make your programs slow.
There are two ways you can use the throw statement. In its simplest form, you can just rethrow the exception in a catch block:
catch(Exception e) { //TODO: Add code to create an entry in event log throw; }
This usage of the throw statement rethrows the exception that was just caught. It can be useful in situations in which you don't want to handle the exception yourself but would like to take other actions (for example, recording the error in an event log, sending an email notification about the error) when an exception occurs and then pass the exception as-is to its caller.
The second way to use the throw statement is to use it to throw explicitly created exceptions, as in this example:
string strMessage = "EndDate should be greater than the StartDate"; ArgumentOutOfRangeException newException = new ArgumentOutOfRangeException(strMessage); throw newException;
In this example, I first create a new instance of the ArgumentOutOfRangeException object and associate a custom error message with it, and then I throw the newly created exception.
You are not required to put this usage of the throw statement inside a catch block because you are just creating and throwing a new exception rather than rethrowing an existing one. You typically use this technique in raising your own custom exceptions. I discuss how to do that later in this chapter.
Another way of throwing an exception is to throw it after wrapping it with additional useful information, as in this example:
catch(ArgumentNullException ane) { //TODO: Add code to create an entry in the log file string strMessage = "CustomerID cannot be null"; ArgumentNullException newException = new ArgumentNullException(strMessage, ane); throw newException; }
TIP
Custom Error Messages When you create an exception object, you should use its constructor that allows you to associate a custom error message rather than use its default constructor. The custom error message can pass specific information about the cause of the error and a possible way to resolve it.
Many times, you need to catch an exception that you cannot handle completely. In such a case you should perform any required processing and throw a more relevant and informative exception to the caller 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 caller code then has more information available to handle the exception appropriately.
It is interesting to note that because InnerException is of type Exception, it also has an InnerException property that may store a reference to another exception object. Therefore, when you throw an exception that stores a reference to another exception in its InnerException property, you are actually propagating a chain of exceptions. This information is very valuable at the time of debugging and allows you to trace the path of a problem to its origin.
The finally Block
The finally block contains code that always executes, whether or not any exception occurs. You use the finally block to write cleanup code that maintains your application in a consistent state and preserves sanitation in the environment. For example, you can write code to close files, database connections, and related input/output resources in a finally block.
TIP
No Code in Between try-catch-finally Blocks When you write try, catch, and finally blocks, they should be in immediate succession of each other. You cannot write any other code between the blocks, although compilers allow you to 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 the finally Block
Add a new Windows form to the project. Name it StepByStep3_3.
-
Place two TextBox controls (txtFileName and txtText), two Label controls (keep their default names), and a Button control (btnSave) on the form and arrange them as shown in Figure 3.5.
Figure 3.5 When you click the Save button, the code in finally block executes, regardless of any exception in the try block.
-
Attach the Click event handler to the btnSave control and add the following code to handle the Click event:
private void btnSave_Click( object sender, System.EventArgs e) { // a StreamWriter writes characters to a stream StreamWriter sw = null; try { sw = new StreamWriter(txtFileName.Text); // Attempt to write the text box // contents in a file foreach(string line in txtText.Lines) sw.WriteLine(line); // This line only executes if there // were no exceptions so far MessageBox.Show( "Contents written, without any exceptions"); } //catches all CLS-compliant exceptions catch(Exception ex) { string msg = String.Format( "Message: {0}\n Stack Trace:\n {1}", ex.Message, ex.StackTrace); MessageBox.Show(msg, ex.GetType().ToString()); goto end; } // finally block is always executed to make sure // that the resources get closed whether or not // the 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 goto label finally { if (sw != null) sw.Close(); MessageBox.Show("Finally block always " + "executes whether or not exception occurs"); } end: MessageBox.Show("Control is at label: end");
}
-
Insert a Main() method to launch the form. Set the form as the startup object for the project.
-
Run the project. You should see a Windows form, as shown in Figure 3.5. Enter a filename and some text. Watch the order of messages. Note that the message box being displayed in the finally block is always displayed prior to the message box displayed by the end label.
TIP
The finally Block Always Executes If you have a finally block associated with a try block, the code in the finally block always executes, whether or not an exception occurs.
Step by Step 3.3 illustrates that the finally block always executes. In addition, if there is a transfer-control statement such as goto, break, or continue in either the try block or the catch block, the control transfer happens after the code in the finally block is executed. What happens if there is a transfer-control statement in the finally block also? That is not an issue because the C# compiler does not allow you to put a transfer-control statement such as goto inside a finally block.
One of the ways the finally statement can be used is in the form of a try-finally block without any catch block. Here is an example:
try { //Write code to allocate some resources } finally { //Write code to Dispose all allocated resources }
NOTE
Throwing Exceptions from the finally Block Although it is perfectly legitimate to throw exceptions from a finally block, it is not recommended. The reason for this is that when you are processing a finally block, you might already have an unhandled exception waiting to be caught.
This use ensures that allocated resources are properly disposed of, no matter what. In fact, C# provides a using statement that does the exact same job but with less code. A typical use of the using statement is as follows:
// Write code to allocate some resource. List the // allocate resources in a comma-separated list inside // the parentheses, with the following using block using(...) { //use the allocated resource } // Here, the Dispose() method is called for all the // objects referenced in the parentheses of the // using statement. There is no need to write // any additional code
An exception occurs when a program encounters any unexpected problem during normal execution.
The FCL provides two main types of exceptions: SystemException and ApplicationException. SystemException represents the exceptions thrown by the CLR, and ApplicationException represents the exceptions thrown by the applications.
The System.Exception class represents the base class for all CLS-compliant exceptions and provides the common functionality for exception handling.
The try block consists of code that may raise an exception. A try block cannot exist on its own. It should be immediately followed by one or more catch blocks or a finally block.
The catch block handles the exception raised by the code in the try block. The CLR looks for a matching catch block to handle the exception; this is the first catch block with either the exact same exception or any of the exception's base classes.
If there are multiple catch blocks associated with a try block, the catch blocks should be arranged in specific-to-general order of exception types.
The throw statement is used to raise an exception.
The finally block is used to enclose code that needs to run, regardless of whether an exception is raised.