You are on page 1of 33

11

Exception Handling

Objectives
• To understand exception and error handling.
• To be able to use try blocks to delineate code in
which an exception may occur.
• To be able to throw exceptions.
• To use catch blocks to specify exception handlers.
• To use the finally block to release resources.
• To understand the C# exception hierarchy.
• To create programmer-defined exceptions.
It is common sense to take a method and try it. If it fails,
admit it frankly and try another. But above all, try something.
Franklin Delano Roosevelt
O! throw away the worser part of it,
And live the purer with the other half.
William Shakespeare
If they’re running and they don’t look where they’re going
I have to come out from somewhere and catch them.
Jerome David Salinger
And oftentimes excusing of a fault
Doth make the fault the worse by the excuse.
William Shakespeare
I never forget a face, but in your case I’ll make an exception.
Groucho (Julius Henry) Marx

© Copyright 1992–2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

550 Exception Handling Chapter 11

Outline
11.1 Introduction
11.2 When Exception Handling Should Be Used
11.3 Other Exception Handling Techniques
11.4 The Basics of C# Exception Handling
11.5 try Blocks
11.6 throwing an Exception
11.7 catching an Exception
11.8 Example: DivideByZero Exception
11.9 Rethrowing an Exception
11.10 Constructors, Destructors and Exception Handling
11.11 Exceptions and Inheritance
11.12 finally Block
11.13 checked and unchecked operators
11.14 StackTrace, Message and InnerException
11.15 User-Defined Exception Classes
Summary • Terminology • Self-Review Exercises • Answers to Self-Review Exercises • Exercises

11.1 Introduction
In this chapter, we introduce exception handling. An exception is an indication that a prob-
lem occurred during the program’s execution. The extensibility of C# can increase the num-
ber and types of errors that can occur. Every new class can add its own error possibilities.
The features presented in this chapter enable programmers to write clearer, more robust,
more fault-tolerant programs. We also consider when exception handling should be used.
Error handling code varies in nature and quantity among software systems depending
on the application and whether the software is a product for release. Publicly released prod-
ucts tend to contain far more error handling code than does “casual” software.
There are many popular means for dealing with errors. Most commonly, error handling
code is interspersed throughout a system’s code. Errors are dealt with at the places in the
code where the errors can occur. The advantage to this approach is that a programmer
reading code can see the error processing in the immediate vicinity of the code and deter-
mine if the proper error checking has been implemented.
The problem with this scheme is that the code in a sense becomes “polluted” with the
error processing. It becomes more difficult for a programmer concerned with the applica-
tion itself to read the code and determine if it is functioning correctly. This can make it dif-
ficult to understand and maintain the application.

© Copyright 1992–2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

Chapter 11 Exception Handling 551

Good Programming Practice 11.1
Using C# exception handling enables the programmer to remove the error handling code
from the “main line” of the program’s execution. This improves program clarity and enhanc-
es modifiability. 11.1

Separating error handling code from the main line of program code is consistent with
the virtues of separability we have discussed in the contexts of both structured program-
ming and object-oriented programming. C# exception handling still enables a programmer
to deal with whatever exceptions the programmer chooses to deal with. The programmer
can deal with all types of exceptions, all exceptions of a certain type or all exceptions of
related types. This makes programs more robust by reducing the likelihood that errors will
not be handled by a program.
Testing and Debugging Tip 11.1
Exception handling helps improve a program’s fault tolerance. It becomes “more pleasant”
to write error-processing code, so programmers are more likely to provide it. 11.1

Software Engineering Observation 11.1
With other programming languages that do not support exception handling, programmers
often delay writing error-processing code, and sometimes programmers simply forget to in-
clude it. This often results in less-robust, and thus inferior, software products. C# forces the
programmer to deal with exception handling from the inception of a project. Still, the pro-
grammer must put considerable effort into incorporating an exception-handling strategy into
software projects. 11.1

In the rest of this chapter, we will see that exceptions are objects of classes derived
from base class Exception. We will show how to deal with “uncaught” exceptions. We
will consider how unexpected exceptions are handled by C#. We will show how related
exception types can be represented by exception derived classes that are derived from a
common exception base class.
Software Engineering Observation 11.2
Exception handling is particularly well-suited to systems of separately developed compo-
nents. Such systems are typical of real-world software systems and products. Exception han-
dling makes it easier to combine the components and have them work together effectively. 11.2

Software Engineering Observation 11.3
It is best to incorporate your exception-handling strategy into a system from the inception of
the design process. It is difficult to add effective exception handling after a system has been
implemented. 11.3

The style and details of exception handling in C# as presented in this chapter are based
in part on the work of Andrew Koenig and Bjarne Stroustrup as presented in their paper,
“Exception Handling for C++ (revised),” published in the Proceedings of the USENIX
C++ Conference held in San Francisco in April, 1990. Their work forms the basis of C++
exception handling. C#’s designers chose to implement an exception handling mechanism
similar to that used in C++.

© Copyright 1992–2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01

a value outside the representable range of values). Exception handling is designed for dealing with synchronous errors. division by zero. The recovery procedure is called an exception handler. Good Programming Practice 11. mouse clicks. 11. libraries and classes that are likely to be widely used. 11.e. Exception handling is slow compared to local processing.1 If an error can be processed locally instead of throwing an exception. • to process exceptions from software components such as methods. Common exam- ples of these exceptions are an out-of-range array subscript. Good Programming Practice 11. invalid method parame- ters and memory exhaustion. Inc. arithmetic overflow (i. 7/2/01 .4 Performance Tip 11. keystrokes and the like.2 Software Engineering Observation 11. then handle it rather than passing the exception on to other regions of your program. Use conventional error handling techniques for local error processing in which a method is able to deal with its own exceptions.2 When Exception Handling Should Be Used Exception handling should be used • to process only exceptional situations where a method is unable to complete its task for reasons it cannot control.3 Avoid using exception handling for purposes other than error handling because this can re- duce program clarity.3 There is another reason to avoid using exception handling techniques for conventional program control. This makes programs clearer. a method that is higher in the execution stack) from that which detected the malfunction.. Exception handling is designed for error processing. A program that carries on an interactive dialog with a user should not use exceptions to process keyboard input problems. Exception handling is not designed to deal with asynchronous events such as disk I/O completions.552 Exception Handling Chapter 11 11.e.2 If your method is capable of handling a given type of exception.4 Use exceptions for malfunctions that must be processed in a different method from where they are detected. • to process exceptions from program components that are not geared to handling those exceptions directly. Exception handling is typically used in situations in which a malfunction will be dealt with in a different scope (i. It is not required that C# implement exception handling for the kind of optimal performance that might be expected of production code. network message arrivals. • to process exceptions on large projects in a uniform manner project wide. 11.1 Exception handling is used in situations in which the system can recover from the mal- function causing the exception.. This will im- prove program execution speed. All Rights Reserved. © Copyright 1992–2002 by Deitel & Associates. 11. which is an infre- quent activity that is often used because a program is about to terminate. do so. and where those components cannot han- dle their own exceptions.

11. By ignoring errors or di- recting the program to abort upon receiving an error. This could annoy or cause damage to the client.” 11.5 11. Exceptions are an appropriate means for dealing with errors produced by library classes.4 The Basics of C# Exception Handling C# exception handling is geared to situations in which the method that detects an error is unable to deal with it. This method of dealing with exceptions can be devastating for software products released to the general public.2 Although it is possible to use exception handling for purposes other than error handling.1 Aborting a program could leave a resource—filestreams. It is unlikely that a library class will perform error processing that would meet the unique needs of all clients. 7/2/01 . If the error is simply ignored. the programmer can then minimize the effect that these errors have on the execution of the program. Common Programming Error 11.4 Using C#’s standardized exception handling rather than having programmers use a diversity of “home-grown” techniques can improve program clarity on large projects.Chapter 11 Exception Handling 553 Performance Tip 11. If the pro- gram aborts. 11.5 The client of a library class will likely have unique error processing in mind for an exception generated in the library class. the program should normally return that resource before program termination. When an exception is thrown. this can reduce program performance. Such a method will throw an exception.3 Other Exception Handling Techniques We have presented various ways of dealing with exceptional situations prior to this chapter. Such a strategy is also inappropriate for mission-critical applications. All Rights Reserved.4 Software Engineering Observation 11. When exceptions happen.3 Good Programming Practice 11. One way for a program to deal with exceptions is to ignore them. For simple applications developed for the programmer’s own use this can be beneficial. By controlling inputs. little or no overhead is imposed by the presence of excep- tion handling code. the effects are minimal. 11.2 Performance Tip 11. there is no guarantee that there will be “anything out there” specifically geared to © Copyright 1992–2002 by Deitel & Associates. the program may finish run- ning but produce bad results. If a program obtains a resource. Resource issues are important here. I/O devices—in a state in which other programs would not be able to acquire the resource. Inc.1 11. Neither of these outcomes would increase user satisfaction with the product. the programmer can either rerun the program with different inputs. And if an error does occur. If the program aborts upon the creation of an unexpected exception. they do incur execution-time overhead. 11.3 When an exception does not occur. development time can be reduced. this will also annoy the client. or insert what error handling code is necessary at that time. hence we would have a so-called “resource leak.

. Thus C# uses the termination model of exception handling rather than the resumption model of exception handling. program control leaves the try block and the catch blocks are searched in order for an appropriate handler (we will soon discuss what makes a handler “appropriate”). If no exceptions are thrown in the try block. The piece of code that deals with exceptions is called an exception handler. 11. If a finally block appears after the last catch block.e. the program allows the user to either terminate or to continue running. When an exception is thrown. Common Programming Error 11. it is possible to communicate information to the exception handler from the vicinity in which the exception occurred. 11. An exception can be thrown from any point inside a try block.6 © Copyright 1992–2002 by Deitel & Associates. Each catch block specifies the type of exception it can catch and contains an exception handler. If there is. C# exits) after the default exception handler runs. 11. the block in which the exception is thrown expires and control cannot return to the throw point. the exception handlers for that block are skipped and the program resumes execution after the last catch block. The point at which the throw is executed is called the throw point. 7/2/01 . 11.2 When an exception occurs. The result of an un- caught exception depends on whether the program is a console application or a Windows application.” If there are no catch blocks following a try block.2 Assuming that after an exception is processed. it is executed regardless of whether or not an exception is thrown. the program terminates (i.554 Exception Handling Chapter 11 processing that kind of exception.6 A key to C#-style exception handling is that the portion of a program or system that handles the exception can be distant from the portion of the program that generates the exception. the code for that catch block is executed.2 When an exception is not caught in a console application. All Rights Reserved. Software Engineering Observation 11. Testing and Debugging Tip 11. control would return to the point at which the exception was thrown and resume execution. control will return to the first statement after the throw can lead to errors.3 Code that may generate an exception is enclosed in a try block. Inc. as we will see. the exception will be caught and handled. If the type of the thrown exception matches the parameter type in one of the catch blocks.3 When an exception is not caught in a Windows application. This information can be harvested from the vicinity in which the exception occurred and placed into the thrown object. The try block is immediately followed by zero or more catch blocks. or from a method called indirectly. Once an exception is thrown. The information is contained within the thrown object. This is done by specifying an object to be thrown with the exception. possibly in an unstable state. the finally block is an ideal place for code that releases resources to prevent “resource leaks. the finally block is required. After the last catch block. a method called directly. It can come from a function call. In the resumption model.2 Testing and Debugging Tip 11. an optional finally block provides code that always executes regardless of whether or not an exception occurs.

5 If it is necessary to pass information about the malfunction that caused an exception. it is called an exception object. all the exception handlers are skipped and control resumes with the first statement after the last exception handler.Chapter 11 Exception Handling 555 11.5 Testing and Debugging Tip 11.6 An object can be thrown without containing information to be passed.6 When an exception is thrown. If a finally block follows the last catch block. If an invalid array subscript is specified. Common Programming Error 11. 11. The operand of a throw can be of any class derived from class System. A try block can be followed by zero or more catch blocks. a method could not complete successfully).3 If a try block executes and no exceptions are thrown. Although an exception can terminate program execution. This strategy is an effective way to avoid resource leaks. Inc. control will proceed to the catch handler.e. This is called throwing an exception. in this case. the code in the finally block executes regardless of whether or not an exception is thrown. All Rights Reserved. control exits the current try block and proceeds to an appropriate catch handler (if one exists) after that try block. 7/2/01 . 11.6 throwing an Exception The throw statement is executed to indicate that an exception has occurred (i. However. Testing and Debugging Tip 11. Any method call can invoke code that might throw an exception or call another method that throws an exception. © Copyright 1992–2002 by Deitel & Associates. That information can then be referenced through the parameter name in the catch handler. still. control will still pro- ceed to the catch handler. the array object throws an IndexOutOfRangeException.3 It is a syntax error to separate the catch handlers that correspond to a particular try block with other code. A try block may appear to contain no error checking and include no throw state- ments. it need not do this. 11. If the operand is an object of class Exception.Exception. knowledge that an exception of this type has been raised may provide sufficient information for the han- dler to do its job correctly. It is also possible that the throw point could be in a deeply nested method call. but code referenced in the try block could certainly cause error-checking code in constructors to execute and possibly throw exceptions.4 A finally block is the best spot to place code that will release resources acquired in a try block. Code in a try block may perform array subscripting on an array object.5 try Blocks An exception that occurs in a try block is normally caught by a handler specified by a catch block immediately following that try block.. such information can be placed in the thrown object. an exception will always terminate the block in which the exception occurred. 11. Testing and Debugging Tip 11. A throw statement specifies an object to be thrown.4 11. It is possible that the throw point could be in a deeply nested scope within a try block.

All Rights Reserved. 11. a programmer can provide a single exception class and catch handler for a group of exceptions. but a break statement is not needed to exit an exception handler in a manner that skips © Copyright 1992–2002 by Deitel & Associates. in this case the exception is considered uncaught.5 Placing catch( Exception e ) before other catch blocks that catch specific types of exceptions would prevent those blocks from ever being executed. the exception object can be created with different instance data such as a type code. If a catch block that catches a base class is defined before one which catches an inherited class. By default. This style of programming is discouraged in object-oriented languages like C# because inheritance and polymorphism takes care of this situation more elegantly. errors often simply happen and then program execution continues.5 It is possible that no handler will match a particular thrown object. The object caught by the handler can be referenced through this parameter. The catch handler can examine this data to distinguish the type of the excep- tion. Each catch block starts with the key- word catch followed by parentheses containing a class name (specifying the type of ex- ception to be caught) and a parameter name. Instead of providing separate exception classes and catch handlers for each. a console application terminates. As this process continues. Rearranging the order in which exception handlers are defined will eliminate this syntax error. If any of these situations arises. Common Programming Error 11. a syntax error will occur. or a syntax error occurs. Although this may seem like the right thing to do. possibly only “hobbling” along. A catch can have only a single argument. Common Programming Error 11. if no handler is found for an exception. Inc. This is followed by a block delineating the exception handling code. There are a couple different instances where this could occur.556 Exception Handling Chapter 11 11. If the programmer accidentally defines two catch blocks that catch the same exception. the code in the catch block is executed. When an exception is caught. Rather. 7/2/01 . Sometimes a program may process many closely related types of exceptions. It is possible that several exception handlers will provide an acceptable match to the type of exception thrown. 11.4 A catch that catches an Exception object catch( Exception e ) means to catch all exceptions. catch( Exception e ) must always be placed last in the list of exception handlers following a try block. A try block followed by several exception handlers resembles a switch statement. A console application will terminate—Windows applications allow the user to terminate or to con- tinue execution.4 Specifying a comma-separated list of catch arguments is a syntax error. This causes the search for a match to continue in the next enclosing try block. Or if an exception handler that catches the Exception class is defined before any others. it may eventually be determined that there is no handler on the execution stack that matches the type of the thrown object. it is not what programmers using other languages without exception handling features are used to doing. As each exception occurs.7 catching an Exception Exception handlers are contained in catch blocks.

if the user types a value that is not an integer in either TextBox. They can look at the situation causing the error.7 Exception handlers can be written a variety of ways. 7/2/01 . The form displays the © Copyright 1992–2002 by Deitel & Associates. All Rights Reserved. whereas all the cases in a switch statement are contained within the single scope of the switch.8 Example: DivideByZero Exception Now let us consider a simple example of exception handling. It becomes more difficult for the programmer to keep track of the larger number of exception cases. The application displays two TextBoxes in which the user can type integers.1 uses try.6 An exception cannot access objects defined within its try block because the try block has expired when the handler begins executing. 11. They can convert one type of exception into another by throwing a different type of excep- tion. An outer try block watches for errors occurring in the original try block’s catch handlers.7 Assuming that an exception thrown from a catch handler will be processed by that handler or any other handler associated with the same try block can lead to logic errors. the program uses an exception to indicate that the user is attempting a division by zero. throw and catch to detect. The first window shows a successful execution. Software Engineering Observation 11. The user typed the values 100 and 7. method divideButton_Click is called to read the two inte- gers from the TextBoxes and pass the integers to method Quotient to calculate the quo- tient of the two values and return a double result. 11. Common Programming Error 11. the catch-all handler gets called. so returning via a return statement would not make sense. They can simply return a status value to their environment. When the user presses the Click To Divide button. the throw point is in a block that has expired. and retry by calling the original method that caused an exception. Consider the sample executions shown in the three output windows. a Forma- tException occurs. Such a return simply returns to the method that called the method con- taining the catch block. not commonplace. Each catch block defines a distinct scope. If no other cases match the exception. 11.7 11. They can rethrow an exception.Chapter 11 Exception Handling 557 over the remaining exception handlers.6 What happens when an exception occurs in an exception handler? The try block that noticed the exception has expired when the exception handler begins running. It is not possible to return to the throw point by issuing a return statement in a catch handler. The application of fig. Also. Again. Common Programming Error 11. Inc. They can perform any necessary recovery and resume execution after the last excep- tion handler. If the user types 0 in the second TextBox.7 Another reason not to use exceptions for conventional flow of control is that these additional exceptions can get in the way of genuine error-type exceptions. 11. Exceptional situations should be rare. etc. indicate and handle exceptions. so excep- tions occurring in an exception handler need to be processed outside the try block in which the original exception was thrown. The catch( Exception e ) handler is similar to a switch statement’s default case. remove the cause of the error.

When we search for Exception in the MSDN documentation we find a whole set of exception classes.Windows. Inc.Forms.Drawing.Label outputLabel.5 1 // Fig 11. 17 private System. 6 using System. To do so.Button divideButton.Container components = null.Form 13 { 14 private System. 5 using System. 20 private System. All Rights Reserved.1 Demonstrating C# exception handling. we must either find an appropriate exception class for a divide-by-zero situation or we must create one. © Copyright 1992–2002 by Deitel & Associates.Forms. C# can test for a division by zero when the values in the division are both integers. 7 using System. In the last window.Windows. 18 private System. 21 22 public DivideByZeroTest() 23 { 24 InitializeComponent(). a zero denominator is entered and the program detects the problem.ComponentModel. throws an exception and issues an appropriate diagnostic message. When the user presses the Click To Divide button.cs 2 // Demonstration of C# exception handling.Data. 25 } 26 27 private void InitializeComponent() 28 { 29 // Visual Studio generated code 30 } Fig.Windows.Label numeratorLabel.Windows. Floating-point division by zero is allowed by C# and results in a value of positive or negative infinity (con- stants for these values can be found in class Double).Forms.TextBox numeratorTextBox.Windows.Windows. This class suits our needs perfectly so we will use it for this example. 19 private System.Forms.5 Associating each type of serious execution-time malfunction with an appropriately named exception class improves program clarity.Forms.ComponentModel. 558 Exception Handling Chapter 11 result of the division performed by method Quotient.TextBox denominatorTextBox. 15 private System.1 : DivideByZeroTest. 7/2/01 . However. In the second output window. 10 11 12 public class DivideByZeroTest : System. our program is going to perform a floating-point division of two integers by casting the first integer to a double before the calculation is performed.Forms.Label denominatorLabel. 16 private System.Windows.Collections.Forms. 11. We would still like to indicate to the user of our program that they are attempting a division by zero. the user entered the string “hello” in the second TextBox. 8 using System. an error message dialog is displayed indicating that an integer must be entered.Windows. One of the exception classes is the DivideByZeroException class. 3 4 using System. 9 using System.Forms. Good Programming Practice 11. 11.

number2 ).EventArgs e) 40 { 41 outputLabel. 78 } 79 } Fig. 42 43 try 44 { 45 int number1 = Int32. 56 MessageBoxButtons. 65 MessageBoxIcon. 36 } 37 38 private void divideButton_Click(object sender.Show( "You must enter two digits ". 76 77 return ( double ) numerator / denominator. 55 "Invalid Number Format".Run(new DivideByZeroTest()). All Rights Reserved. Used to demonstrate 70 // throwing an exception when a divide-by-zero error 71 // is encountered.ToString( "0. int denominator ) 73 { 74 if ( denominator == 0 ) 75 throw new DivideByZeroException(). 49 outputLabel. 39 System.Message.Text ). 63 "Attempted to Divide by Zero". 72 public double Quotient ( int numerator. 66 } 67 } // end of divideButton_Click 68 69 // Definition of method Quotient. © Copyright 1992–2002 by Deitel & Associates.000" ). Chapter 11 Exception Handling 559 31 32 [STAThread] 33 static void Main() 34 { 35 Application.1 Demonstrating C# exception handling.Error ).Parse( denominatorTextBox.Text = result. 7/2/01 .Show( dbze. 64 MessageBoxButtons. 50 } 51 52 catch ( FormatException fe ) 53 { // User did not enter two digits 54 MessageBox. 57 MessageBoxIcon.OK.Parse( numeratorTextBox. Inc.Text ). 47 48 double result = Quotient( number1.Error ).Text = "". 11. 58 } 59 60 catch ( DivideByZeroException dbze ) 61 { // User attmepted to divide by zero 62 MessageBox. 46 int number2 = Int32.OK.

The method then proceeds with a try block (lines 43–50) that encloses the code that may throw an exception and that must be abandoned if an exception occurs. The division that can cause the divide-by-zero error is not explicitly listed in the try block. This method throws a FormatException if the string being converted is not a valid integer. method divideButton_Click (lines 38–67) is called. the call to method Quotient (line 48) invokes the code that attempts © Copyright 1992–2002 by Deitel & Associates.Parse to convert strings to int values. After the user enters the denominator and clicks on divideButton.1 Demonstrating C# exception handling. All Rights Reserved. Inc. 7/2/01 . 11. The application’s con- structor (lines 22–25) calls method InitializeComponent which builds a graphical user interface with three Labels and two TextBoxes. Consider the DivideByZeroTest class (lines 12–75). Rather. 560 Exception Handling Chapter 11 Fig. The statements that read the integers from the Text- Boxes (lines 45–46) each use method Int32.

In Fig. these variables would be destroyed. Only the matching catch handler executes if an exception is thrown. Note that when Quotient throws the DivideByZeroException. All Rights Reserved. and the message is displayed using the exception’s Mes- sage property (line 64).8. errors may surface through explicitly mentioned code in a try block. In general. Here.e. the body of the if executes a throw statement that creates and throws a new DivideByZeroException object.7 Now let us examine method Quotient. 7/2/01 . This would cause any of its local variables to be destroyed—objects that were referenced by local variables in the block have their reference counts decremented accordingly (and are possibly marked for garbage collection). but exception handlers can be more elaborate than this. then the catch handlers are skipped and execution resumes with the first line of code after the catch handlers. In general. the division is performed and the result of the division is returned to the point of invocation of method Quotient in the try block (line 48). In Fig. If this exception is thrown. The catch blocks are skipped and the divideButton_Click method completes execu- tion normally.Parse) and the second catch block speci- fies that it will catch exception objects of type DivideByZeroException (this type matches the type of the object thrown in method Quotient). method divideButton_Click simply returns. Method Quotient (lines 69–75) throws the DivideByZeroExcep- tion object. The string that is returned is shown in a MessageBox. through calls to a method. control proceeds to the first statement after the last catch block. When the if statement (lines 71–72) deter- mines that denominator is zero. After exe- cuting an exception handler. If the code in the try block does not throw an exception. Both our exception handlers simply display an error message dialog. Inc. Quotient’s block expires. as we will see momentarily.Chapter 11 Exception Handling 561 the division. or even through deeply nested method calls initiated by code in a try block.7 With exception handling. The try block is immediately followed by two catch blocks—lines 52–58 contain the exception handler for the FormatException and lines 60–66 contain the exception handler for the DivideByZeroException. 11.. has the exact same type as the thrown excep- tion or is a super class of the thrown exception). when an exception is thrown within a try block. This object will be caught by the catch block specifying type DivideByZeroException after the try block (lines 60–66). If denominator is not zero. but the program could con- tinue executing more statements after the catch blocks. no exception is thrown. 11. We then display the result of the calculation in the third Label. the exception is caught by a catch block that specifies an appropriate type that matches the thrown exception (i. This helps ensure robust applications that contribute to what is called mission-critical com- puting or business-critical computing. 11. too. a program can continue executing after dealing with a problem.8. The thrown object is received in parameter dbze (line 60) specified in the second catch handler. Testing and Debugging Tip 11. the first catch block speci- fies that it will catch exception objects of type FormatException (this type matches the type of the object thrown in method Int32. if there were local variables created in the try block prior to the exception being thrown. the try block from which the method was called also expires before line 49 can execute. © Copyright 1992–2002 by Deitel & Associates.

the handler can still rethrow the exception for further processing outside the handler. ApplicationException Fig. Inc. Other exceptions can be found in the C# on-line documentation and in the help provided with Visual Studio. and regardless of whether it does any pro- cessing on that exception.e. but this is a poor program- ming practice. In this case. © Copyright 1992–2002 by Deitel & Associates.2 Some derived classes of the Exception class.562 Exception Handling Chapter 11 If a FormatException is generated by lines 45–46.9 Rethrowing an Exception It is possible that the catch handler that catches an exception may decide it cannot process the exception or it may want to let some other catch handler handle it. Before each object is garbage col- lected. What happens when an error is detected in a constructor? The problem is that a constructor cannot return a value. the method terminates in this example). the handler that received Exception e can simply rethrow the exception with the statement throw e.2 through 11. 11. A thrown exception passes to the outside world the information about the failed constructor and the responsibility to deal with the failure. 11. the try block expires and exe- cution continues with the exception handler at line 52. Exceptions thrown in constructors cause objects built as part of the object being con- structed to be marked for eventual garbage collection. A rethrown exception is detected by the next enclosing try block and is handled by an exception handler listed after that enclosing try block. 11.4 list many of C#’s Exceptions hierarchically. Even if a handler can process an exception. Once again.. An error message dialog is displayed to tell the user to enter integers. Derived classes of the Exception class. 11. C# does not guarantee the order in which objects will be garbage collected and therefore it does not guarantee the order in which finalize methods will be called. so how do we let the program know that an object has not been properly constructed? One scheme is simply to return the improperly constructed object and hope that anyone using the object would make appropriate tests to determine that the object is in fact bad. Another scheme is to set some global variable outside the constructor.10 Constructors. Destructors and Exception Handling Let us now deal with an issue that has yet to be satisfactorily resolved.11 Exceptions and Inheritance Figures 11. All Rights Reserved. Such a throw rethrows the exception to the next enclosing try block. 7/2/01 . its finalize method will be called. then the divideButton_Click method continues with the next valid statement after the catch blocks (i.

All Rights Reserved. Figure 11. IOException SystemException SoapException WebException Fig. 11. Derived classes of SystemException. This can allow for polymorphic processing of related errors. 11. 11. 7/2/01 .4 Some Derived classes of SystemException. it can also catch all objects of derived classes of that base class. If a catch is written to catch exception objects of a base class type.3 lists C#’s IOExceptions.2 Some derived classes of the Exception class. ArithmeticException ArgumentException DataException IndexOutOfRangeException NullReferenceException OutOfMemoryException ExternalException SecurityException StackOverflowException ThreadInterruptedException TypeInitializationException Fig. Various exception classes can be derived from a common base class. One could certainly catch each derived class exception object indi- © Copyright 1992–2002 by Deitel & Associates. DirectoryNotFoundException EndOfStreamException FileLoadException FileNotFoundException Fig. Derived classes of IOException. Using inheritance with exceptions enables an exception handler to catch related errors with a concise notation. These are all exceptions that can occur during input/output and file processing.Chapter 11 Exception Handling 563 Derived classes of the Exception class. Inc.3 Derived classes of IOException.

the fi- nally block should close any files opened in the try block. an exception of type IndexOutOfRangeEx- ception is thrown.8 Testing and Debugging Tip 11. Most memory leak problems are solved by C#’s garbage collection. } catch ( AKindOfException ex1 ) { exception-handling statements.8 If there are any catch blocks present. } finally { statement. These are called run-time exceptions and they derive from class SystemException. Many of these exceptions can be avoided by coding properly. these problems can only be detected at run-time so they are considered run-time exceptions.12 finally Block Programs that obtain certain types of resources must explicitly return those resources to the system to avoid so-called resource leaks. Inc.8 Actually. Otherwise. But other kinds of resource leaks can occur in C#. For example. For example. This only makes sense if the handling behavior would be the same for all derived classes of course. There is a subtle issue here. hence. These problems can usually only be detected at run-time. Software Engineering Observation 11. but only if programmers erroneously keep references to unwanted objects. C# performs automatic garbage col- lection of memory no longer needed by programs.8 A finally block typically contains code to release resources acquired in its correspond- ing try block. the finally block is optional. this is an effective way to eliminate resource leaks. catch each derived class exception individually. Thus. 11. In programming languages like C and C++ the most common kind of resource leak is a memory leak. 11. All Rights Reserved. memory leaks can occur. 11. it must be present. but it is more concise to catch the base class exception object instead. Some exceptions can occur at any point during the execution of the program.564 Exception Handling Chapter 11 vidually. Again. © Copyright 1992–2002 by Deitel & Associates. } catch ( AnotherKindOfException ex2 ) { exception-handling statements. thus avoiding most memory leaks. 7/2/01 . resource-release statements. Another run-time exception occurs when your program creates an object reference but has not yet created an object and attached it to the reference. it is a run-time exception. C# does not completely eliminate memory leaks. if your program attempts to access an out-of-range array subscript. resource-acquisition statements. C# will not garbage collect an object until there are no more references to the object. If it is present it is placed after the last of a try block’s catch blocks as follows: try { statements. If no catch blocks are written. Attempting to use such a null reference causes a NullReferenceException to be thrown.

Inc. method DoesNotThrowException is called. Control proceeds past the finally block.5 demonstrates that the finally block executes even if an exception is not thrown in the corresponding try block. Chapter 11 Exception Handling 565 } C# guarantees that a finally block will be executed regardless of what occurs in the try and catch blocks. the best code to place in a finally block is resource-release code. All Rights Reserved.4 The C# application of Fig. catches it (line 30) and rethrows it (line 34). Method Main begins executing. No exception is thrown in its try block. 11. 5 6 class UsingExceptions 7 { 8 static void Main( string[] args ) 9 { 10 try Fig. so the catch block is skipped. © Copyright 1992–2002 by Deitel & Associates. The finally block is guaranteed to execute once and only once regardless of errors thrown or caught. Next. The rethrown exception is detected in the try block in Main (lines 10–13) and handled by the catch block (lines 14–18). enters its try block and immediately calls ThrowException. The rethrown exception will be handled in Main. Its possible to place all resource management code into catch blocks. break or continue statement. ThrowException and DoesNotThrowException. If no exceptions are thrown. if an error is thrown in a catch block and even if the try block is exited via a return. This makes these resources immediately available for reuse and can improve program performance. but first the finally block (lines 38–42) executes. the try block immediately executes and the resources are never freed. resources should be released as soon as it is apparent that they are no longer need- ed. Method ThrowException throws an Exception (line 28). 11.5 : UsingExceptions.5 Using exceptions with a finally block. Methods ThrowException and DoesNotThrowException are declared static so they can be called directly from Main (another static method). 11. 7/2/01 .cs 2 // Using exceptions with a finally block 3 4 using System. but if you have many catch blocks you need to repeat a lot of code. but the finally block nevertheless exe- cutes. the try block executes normally and the resources are freed after they have been used. All of the resource-manage- ment code has been placed within the try block. 1 // Fig 11. Suppose a program needs to access a large amount of resources in order to perform some computation. The program contains methods Main. Because C# guarantees the execution of such blocks. Performance Tip 11. This means that the finally block will execute if an error is thrown in the try block and caught. if an error is thrown in the try block and uncaught. But if an exception is thrown. The simplest way to accomplish this task is to use a finally block. Because there are no statements fol- lowing finally control returns to Main and the program terminates.4 As a rule.

Error. 63 } 64 Fig.Error. 20 } 21 22 public static void ThrowException() 23 { 24 //Throw an exception and immediately catch it 25 try 26 { 27 Console. 28 throw new Exception(). All Rights Reserved.WriteLine( "Finally executed in " + 41 "ThrowException" ). //generate Exception 29 } 30 catch ( Exception e ) 31 { 32 Console.WriteLine( 17 "Exception handled in Main" ). 34 throw e. 42 } 43 44 //any code here would not be reached 45 46 } 47 48 public static void DoesNotThrowException() 49 { 50 try 51 { 52 Console. 13 } 14 catch ( Exception e ) 15 { 16 Console.ToString() ).WriteLine( "Exception handled in " + 33 "method ThrowException" ).5 Using exceptions with a finally block. Inc.WriteLine( 53 "Method DoesNotThrowException" ). // rethrow e for further processing 35 36 // any code here would not be reached 37 } 38 finally 39 { 40 Console. 566 Exception Handling Chapter 11 11 { 12 ThrowException().WriteLine( e.Error. 18 } 19 DoesNotThrowException(). © Copyright 1992–2002 by Deitel & Associates.Error. 11.WriteLine( "Finally executed in " + 62 "DoesNotThrowException" ). 7/2/01 .WriteLine( "Method ThrowException" ). 54 } 55 catch( Exception e) 56 { 57 Console. 58 } 59 finally 60 { 61 Console.Error.

9 Avoid placing code that can throw an exception in a finally block. the finally block will execute. place one try block around a significant portion of your code.6 Software Engineering Observation 11. if an exception is thrown in the finally block. that exception is lost and the more recent exception is processed. 11. If this hap- pens. Chapter 11 Exception Handling 567 65 Console.5 Using exceptions with a finally block. then follow that try block with catch blocks that handle each of the things that can go wrong. if there was an exception that had not yet been caught. when control enters the local finally block. 11. the continuation action will be for that exception to be processed in the next enclosing try block. the finally block will be executed even if the try block is exited with return. This is dangerous.9 If a try block has a corresponding finally block. All Rights Reserved. the finally block could also throw an exception.9 Good Programming Practice 11. Normally. As we have seen. then behave appropriately (we will call this finally’s “continuation action”) depending on the reason it was entered. such as a try completing successfully. For example. break or continue will occur.6 C#’s exception handling mechanism is intended to remove error-processing code from the main line of a program’s code to improve program clarity. Inc. or a program control statement like a return. This makes programs dif- ficult to read. an exception being thrown and then handled by a local catch. an exception being thrown for which no local catch is available. 67 } 68 } Method ThrowException Exception handled in method ThrowException Finally executed in ThrowException Exception handled in Main Method DoesNotThrowException Finally executed in DoesNotThrowException End of method DoesNotThrowException Fig. 11. then follow the catch blocks with a single finally block.8 Testing and Debugging Tip 11. 11. Do not place try-catch- finally around every statement that may throw an exception. then the effect of the return. 11. a finally block may be entered for a variety of reasons. the first exception will be lost. break or continue being executed. Rather. break or continue.8 If an exception is thrown for which no local catch is available. Unfortunately. 7/2/01 .WriteLine( "End of method " + 66 "DoesNotThrowException" ).9 © Copyright 1992–2002 by Deitel & Associates. Common Programming Error 11.

Out.Out.Overflow.WriteLine( "Exception: {0}". at overflow. 3 4 using System. C# allows values of negative and positive in- finity.OverflowException: Exception of type System. If the checked operator is used and overflow occurs. If you use a long you get 64-bits.WriteLine( "Product: {0}". 25 product = unchecked( a * b ). Regular ints are limited to 32-bits. 568 Exception Handling Chapter 11 11. This means that overflow is impossible when dealing with floating point values. While your program will probably run to completion in this case. 1 // Fig 11.6 : overflow. 11 int a = 45000. Exception: System. the overflowing bits will be silently discarded. 26 Console. 12 int b = 56000.Out. All Rights Reserved. Ofe ).." ). the data that is generated will be wrong.cs 2 // Showing the use of the checked and unchecked operators.. Sometimes an overflow is not important. 27 } Testing overflowing integers.13 checked and unchecked operators When dealing with floating point arithmetic. an overflow will create unstable data. a System. product ). 7/2/01 . Inc.OverflowEx- ception will be thrown (inherited from the SystemException class). If the unchecked operator is used. In- tegers in C# are limited though.cs:line 25 Product: 0 Prodcut: -1774967296 Fig. But you can still experience integer overflow.Out. 18 } 19 catch ( System... © Copyright 1992–2002 by Deitel & Associates. product ). But if you need the number to be exact.Over- flowException was thrown. 11. C# provides checked and unchecked operators to deal with these situations. 14 15 try 16 { 17 product = checked( a * b ). 22 } 23 24 Console. 5 6 class Overflow 7 { 8 static void Main( string[] args ) 9 { 10 Console.WriteLine( "Testing overflowing integers.WriteLine( "Product: {0}". 13 int product = 0.6 Testing checked and unchecked operators.Main(String[] args) in C:\over- flow\Class1.OverflowException Ofe ) 20 { 21 Console.

10 All Exception objects contain a StackTrace property that can be used to print a stack trace for the object. 11. The stack trace shows the complete method call stack. The operation succeeds. The informa- tionString stored in the Exception may be queried with property Message. Class Exception offers two properties that make outputting an error statement easier. The Exception class has a StackTrace property that contains the method call stack and a Message property which holds an error message. the optional character string that was supplied when the exception was constructed. All Rights Reserved. but the application did not abort. Inc. By printing the StackTrace property for an Exception object that has been caught. This information is helpful in debugging a program. its resulting string in- cludes the descriptive string that was supplied to the constructor. 11. From the output we see that the exception is of type System. Message and InnerException Exceptions derive from class Exception. and a complete execution stack trace. a program can print the method call stack. The second constructor public Exception( string informationString ) takes an argument informationString which is descriptive information about this kind of Exception that will be carried in every object of this class. Lines 19–22 catch the exception an print it out. 7/2/01 .6 we show how the checked and unchecked operators work. Lines 24–26 then attempt to do the calculation with the unchecked operator.12 There are several constructors for class Exception.10 Testing and Debugging Tip 11. Clearly this is not the value that we were expecting. This is often helpful in testing and de- bugging. We enclose the operation in a try block in order to catch the exception that arises. This lets the programmer see the path of execution that led to the exception file-by-file (and thus class-by-class) and method-by-method.11 An exception that is not caught eventually causes C#’s default exception handler to run. no exceptions are thrown. we consider an example that exercises the StackTrace property and the Message property.OverflowException.Chapter 11 Exception Handling 569 In Fig. But when we print the value of product (line 26) we see that it has the value -1774967296.14 StackTrace. This displays the name of the exception.12 When Message property is accessed on any exception object. 11. In lines 11 and 12 we set integers a and b to values that will guarantee an overflow when they are mul- tiplied. In this section. Lines 15–22 attempt to do the calculation with the checked operator. The first constructor public Exception() takes no arguments. 11. © Copyright 1992–2002 by Deitel & Associates. 11. Testing and Debugging Tip 11.11 Testing and Debugging Tip 11.

11. 23 } 24 } 25 26 public static void Method1() 27 { 28 Method2().. Prop- erty Message returns the descriptive string stored in an exception. 1 // Fig.13 Exception classes have a constructor that accepts a string. This al- lows exceptions to be embedded in other exceptions. 7/2/01 .WriteLine( "Exception: \n{0}".7 Different ways of printing an exception. 22 e. 11. The inner- Exception is placed into the innerException property of the Exception. 21 Console.Error.WriteLine( "InnerException: \n{0}".e. 11. 18 Console.StackTrace ).Message ). 19 e. Fig. public Exception ( string informationString.7 demonstrates Message. 3 4 using System.Error. StackTrace and InnerException. 570 Exception Handling Chapter 11 Testing and Debugging Tip 11. © Copyright 1992–2002 by Deitel & Associates.cs 2 // demonstrating printing an exception.WriteLine( "StackTrace: \n{0}". Exception InnerException ) The informationString is placed into the Message property again. All Rights Reserved. e. 5 6 class UsingExceptions 7 { 8 public static void Main( string[] args ) 9 { 10 try 11 { 12 Method1(). 13 } 14 15 catch ( Exception e ) 16 { 17 Console. Property Stack- Trace returns a list of the methods that had not completed execution when the exception was thrown (i. exceptions also have a ToString method. the ToString method prints the name of the exception. Using this form of the constructor is helpful in determining the source of the exception via property Message.7: properties. all methods currently residing on the method call stack).WriteLine( "Message: \n{0}". e.ToString() ). For exceptions. Figure 11. the Message property and the StackTrace property.InnerException ).Error. any InnerException it may have.13 The third constructor for class Exception takes a string and another instance of an Exception class. Like all objects in C#. 20 Console.Error. Inc.

Method3() in C:\properties\Class1.cs:line 33 at properties. The stack trace reflects the throw point in the code (i.Exception: Exception thrown in method3 ---> System.cs:line 17 Fig. a stack trace message is gen- erated and stored in the Exception object. the stack unwinds to the first method in the method call stack in © Copyright 1992–2002 by Deitel & Associates. 39 new Exception( "inner" ) ).Exception: inner at properties.Properties.Properties.cs:line 33 at properties.cs:line 38 at properties. Method1 invokes Method2 and Method2 invokes Method3.Method2() in C:\properties\Class1.Properties.Properties.Properties. 11.Method2() in C:\properties\Class1.Method1() in C:\properties\Class1. All Rights Reserved. When Method3 throws an Exception (line 36).Exception: inner Message: Exception thrown in method3 StackTrace: at properties. In the program.Properties. line 36). Main invokes Method1. 40 } 41 } Exception: System.7 Different ways of printing an exception.e.Properties..cs:line 38 at properties. Inc. Chapter 11 Exception Handling 571 29 } 30 31 public static void Method2() 32 { 33 Method3().Method3() in C:\properties\Class1.Main(String[] args) in C:\proper- ties\Class1.Main(String[] args) in C:\proper- ties\Class1. At this point. 7/2/01 .cs:line 43 at properties.cs:line 17 InnerException: System. the method call stack for the program is Method3 Method2 Method1 Main with the last method called (Method3) at the top and the first method called (Main) at the bottom.Properties.Method1() in C:\properties\Class1. Then.cs:line 43 at properties. 34 } 35 36 public static void Method3() 37 { 38 throw new Exception( "Exception thrown in method3".

32 private System.Windows.Label numeratorLabel.1 except we create our own user-defined exception class to deal with divide by zero exceptions.Drawing.ComponentModel.Button divideButton.Windows. 7 using System.ComponentModel.TextBox numeratorTextBox.Windows. 6 using System.15 User-Defined Exception Classes Exception classes are governed by the same C# rules that govern all classes.Form 25 { 26 private System.Windows.Container components = null. 3 4 using System. Inc. This example is identical to Fig. 11. The catch handler then uses ToString.e.Forms." ) 20 { 21 } 22 } 23 24 public class DivideByZeroTest : System. InnerException." ) 15 { 16 } 17 18 public DivideByZeroException( string message ) 19 : base( "Attempted to divide by zero.Data. among other things.Windows. Fig. 30 private System. 5 using System.Windows.Collections.Forms. All Rights Reserved. 10 11 public class DivideByZeroException : System. 572 Exception Handling Chapter 11 which the exception can be caught (i. This means.TextBox denominatorTextBox. Mes- sage and StackTrace on the Exception object e to produce the output. 1 // Fig 11.8. 9 using System.Forms.cs 2 // Demonstrating C# exception handling. 28 private System. In Fig. 27 private System. that exception classes can be inherited from.Label denominatorLabel.Forms.8 Demonstrating C# exception handling. 33 34 public DivideByZeroTest() 35 { 36 InitializeComponent(). we show how to create exception classes. 11. 8 using System.. 31 private System.ArithmeticException 12 { 13 public DivideByZeroException() 14 : base( "Attempted to divide by zero.Windows.8 : DivideByZero. © Copyright 1992–2002 by Deitel & Associates. Notice that the line numbers in the output window correspond to the line numbers in the program. 11. 7/2/01 .Forms.Label outputLabel. main because it contains a catch handler for Exception). 11.Windows. 29 private System.Forms.Forms.Forms. Users can create their own derived classes that utilize much of the functionality of existing exception classes.

All Rights Reserved. 67 "Invalid Number Format".Show( dbze. int denominator ) 86 { 87 if ( denominator == 0 ) 88 throw new DivideByZeroException(). 11. Used to demonstrate 83 // throwing an exception when a divide-by-zero error 84 // is encountered 85 public double Quotient( int numerator. 61 outputLabel.OK.Show( "You must enter two digits ". 48 } 49 50 private void divideButton_Click( object sender.OK.Parse( denominatorTextBox.EventArgs e ) 52 { 53 outputLabel. 62 } 63 64 catch ( FormatException fe ) 65 { // User did not enter two digits 66 MessageBox. Inc. Chapter 11 Exception Handling 573 37 } 38 39 private void InitializeComponent() 40 { 41 // Visual Studio generated code 42 } 43 44 [STAThread] 45 static void Main() 46 { 47 Application. © Copyright 1992–2002 by Deitel & Associates. 77 MessageBoxIcon. 54 55 try 56 { 57 int number1 = Int32. 76 MessageBoxButtons. 70 } 71 72 catch ( DivideByZeroException dbze ) 73 { // User attempted to divide by zero 74 MessageBox.Text ).Text ). 59 60 double result = Quotient( number1.000" ).Message.Text = result.Run( new DivideByZeroTest() ).Text = "". 89 90 return ( double ) numerator / denominator. 68 MessageBoxButtons.Parse( numeratorTextBox. 51 System. 58 int number2 = Int32. 75 "Attempted to Divide by Zero". 7/2/01 .Error ).Error ). 69 MessageBoxIcon.ToString( "0. 78 } 79 80 } // end of divideButton_Click 81 82 // Definition of method Quotient. number2 ).8 Demonstrating C# exception handling. Fig.

11. error handling code is interspersed throughout a system’s code. © Copyright 1992–2002 by Deitel & Associates. All Rights Reserved. 7/2/01 . SUMMARY • An exception is an indication that a problem occurred during the program’s execution. • Publicly released products tend to contain far more error handling code than does “casual” soft- ware.8 Demonstrating C# exception handling. • Error handling code varies in nature and quantity among software systems depending on the ap- plication and whether the software is a product for release. 574 Exception Handling Chapter 11 91 } 92 } Fig. • Most commonly. Inc.

• Each catch block specifies the type of exception it can catch and contains an exception handler. the block in which the exception is thrown expires and control cannot return to the throw point. all the exception handlers are skipped and control resumes with the first statement after the last exception handler. • When an exception occurs. • Ignoring errors can be devastating for software products released to the general public. • An exception will always terminate the block in which the exception occurred. All Rights Reserved. • It is possible that several exception handlers will provide an acceptable match to the type of ex- ception thrown. an optional finally block provides code that always executes re- gardless of whether or not an exception occurs. 7/2/01 . • If a finally block follows the last catch block. • When an exception is not caught in a console application. • C# forces the programmer to deal with exception handling from the inception of a project.” • C# exception handling is geared to situations in which the method that detects an error is unable to deal with it. • Exception handling is designed for dealing with synchronous errors. it is possible to communicate information to the exception handler from the vicinity in which the exception occurred. C# exits) after the default exception handler runs. • When an exception is not caught in a Windows application. • Use conventional error handling techniques for local error processing in which a method is able to deal with its own exceptions. Inc. • A throw statement specifies an object to be thrown. • The finally block is an ideal place for code that releases resources to prevent “resource leaks. • Once an exception is thrown. • Exception handling is slow compared to local processing.. © Copyright 1992–2002 by Deitel & Associates.e. • If a try block executes and no exceptions are thrown. • Aborting a program could leave a resource in a state in which other programs would not be able to acquire the resource. hence we would have a so-called “resource leak. the finally block is required. the program allows the user to either terminate or to continue running. possibly in an unstable state. • Exception handling is typically used in situations in which a malfunction will be dealt with in a different scope (i. • Code that may generate an exception is enclosed in a try block. • Exception handlers are contained in catch blocks.” • If there are no catch blocks following a try block. • The operand of a throw can be of any class derived from class System. • The piece of code that deals with exceptions is called an exception handler. the code in the finally block executes re- gardless of whether or not an exception is thrown. • After the last catch block. a method that is higher in the execution stack) from that which detected the malfunction. the program terminates (i.. then handle it rather than passing the exception on to other regions of your program. • If your method is capable of handling a given type of exception.e.Exception.Chapter 11 Exception Handling 575 • Using C# exception handling enables the programmer to remove the error handling code from the “main line” of the program’s execution.

this is an effective way to eliminate resource leaks. • If the unchecked operator is used. an exception being thrown and then handled by a local catch. • C# provides checked and unchecked operators to deal with integer overflow. or a program control statement like a return. the optional character string that was supplied when the exception was constructed. • Programs that obtain certain types of resources must explicitly return those resources to the system to avoid so-called resource leaks. • Floating-point division by zero is allowed by C# and results in a value of positive or negative in- finity (constants for these values can be found in class Double). • By printing the StackTrace property for an Exception object that has been caught. or a syntax error occurs. Inc. control proceeds to the first statement after the last catch block. through calls to a method. • The Exception class has a StackTrace property that contains the method call stack and a Message property which holds an error message. • The C# default exception handler displays the name of the exception. a System. and regardless of whether it does any processing on that exception.OverflowException will be thrown (inherited from the SystemException class). • A finally block typically contains code to release resources acquired in its corresponding try block. the overflowing bits will be silently discarded. such as a try completing successfully. thus avoid- ing most memory leaks. • A finally block may be entered for a variety of reasons. • Exception classes are similar to other classes in C# in that they can be inherited from. and a complete execution stack trace. • If the checked operator is used and overflow occurs. an exception being thrown for which no local catch is available. © Copyright 1992–2002 by Deitel & Associates. break or continue being executed. a pro- gram can print the method call stack. • In general. • After executing an exception handler. • Each catch block defines a distinct scope. • A rethrown exception is detected by the next enclosing try block and is handled by an exception handler listed after that enclosing try block. catch( Exception e ). All Rights Reserved. • Even if a handler can process an exception. the handler can still rethrow the exception for further processing outside the han- dler. • A thrown exception passes to the outside world the information about the failed constructor and the responsibility to deal with the failure. • C# performs automatic garbage collection of memory no longer needed by programs.576 Exception Handling Chapter 11 • The catch-all handler. • The InnerException is placed into the InnerException property of the Exception which allows exceptions to be embedded in other exceptions. • It is not possible to return to the throw point by issuing a return statement in a catch handler. • C# guarantees that a finally block will be executed regardless of what occurs in the try and catch blocks. • The informationString stored in the Exception may be queried with property Mes- sage. errors may surface through explicitly mentioned code in a try block. 7/2/01 . must always be placed last in the list of ex- ception handlers following a try block. or even through deeply nested method calls initiated by code in a try block.

any InnerExcep- tion it may have. the ToString method prints the name of the exception. All Rights Reserved. • The stack trace reflects the throw point in the code. Inc. the Message property and the StackTrace property.Chapter 11 Exception Handling 577 • For exceptions. 7/2/01 . TERMINOLOGY arithmetic overflow ArithmeticException asynchronous events business-critical computing call stack catch block catch handler catch-all handler constructor failure conventional error handling techniques default exception handler disk I/O completion division by zero Error handling code error-processing code Exception exception handler exception handling exception object exception derived class exception base class execution stack fault-tolerant programs finally block FormatException garbage collection IndexOutOfRangeException inheritance with exceptions invalid array subscript IOException memory exhaustion memory leak Message property method call stack mission-critical application NullReferenceException object to be thrown out-of-range array subscript overflow polymorphic processing of related errors printStackTrace program’s fault tolerance Publicly released products reference counts release resources © Copyright 1992–2002 by Deitel & Associates.

f) In C#. the method is said to __________ an exception. an uncaught exception results in immediate termination. a) Exception handling deals with __________ errors. g) In a Windows program. k) In order to force an exception to be thrown when arithmetic overflow occurs. e) The finally block will always execute regardless of what occurs in a try and catch block. c) The __________ block always gets executed. but not __________ errors. 7/2/01 .2 State whether each of the following is true or false. h) Exceptions can be rethrown. h) An uncaught exception will cause a console application to __________. © Copyright 1992–2002 by Deitel & Associates. c) Memory exhaustion is an event that might throw an exception. b) Publicly released software generally has very little exception handling code. b) When an exception is created. g) If the catch-all exception handler is declared before another exception handler. explain why. i) The Int32.578 Exception Handling Chapter 11 resource issue resource leak resource-release code resumption model of exception handling rethrow an exception run-time exceptions stack trace message standardized exception handling synchronous error System. k) Exceptions can only be thrown by methods explicitly called in a try block. If false. All Rights Reserved. f) Blocks of code that perform exception handling are designated with the __________ key- word. i) The checked operator causes a syntax error when arithmetic overflow occurs. the __________ operator is used. Inc.Parse method throws a __________ exception. a __________ error occurs. a) Exceptions should always be handled outside of the methods scope. j) The Message property holds a trace of the call stack. d) A finally block is always optional after a try block. d) Exception objects are derived from the __________ class.Exception SystemException termination model of exception handling throw throw an exception throw point throwing an exception thrown exception try block uncaught exception SELF-REVIEW EXERCISES 11.1 Answer each of the following questions. e) The place where an exception is created is called the __________. j) Runtime exceptions are derived from the __________ class. 11. it is possible to return to the throw point of an exception.

All Rights Reserved. other scopes. a finally block is required. f) False. d) System. h) True. explicitly or implicitly. e) throw point. 11. If there are no catch statements. Publicly released software generally has a lot of exception handling code. 11. 7/2/01 .7 Write a C# program that illustrates rethrowing an exception.8 Write a C# program which shows that a method with its own try block does not have to catch every possible error generated within the try. © Copyright 1992–2002 by Deitel & Associates. Inc. and be handled in. i) FormatException.Chapter 11 Exception Handling 579 ANSWERS TO SELF-REVIEW EXERCISES 11. j) SystemException. An uncaught exception in a Windows ap- plication provides the user with the option of terminating or continuing in a possibly unstable state. If you try to catch a base class exception type before a derived class type. c) finally. c) True. asynchronous. It is impossible to return to the throw point in C#. e) True.5 Write a C# program that shows that the order of exception handlers is important.Exception. d) False. i) True. EXERCISES 11. Write a program to demonstrate that the catch specifying the base class catches derived class ex- ceptions.3 Use inheritance to create an exception base class and various exception derived classes. the compiler should generate errors.1 a) synchronous. b) False. g) False. k) False. h) terminate.6 Write a C# program that shows a constructor passing information about constructor failure to an exception handler after a try block. k) checked. Some exceptions can slip through to.4 Write a C# program that demonstrates how various exceptions are caught with catch ( Exception e ) 11. Excep- tions can be thrown by any methods called in a try block. j) False.2 a) True. f) try. 11. 11. 11. The StackTrace property holds a trace of the call stack. b) throw. Explain why these errors occur. g) syntax.

560. 572 Stroustrup. 570 G positive infinity 558 catch block 554. 562. 570 structured programming 551 exception derived class 551 mission-critical application 553 synchronous error 552 exception handler 550. 556 NullReferenceException throw point 554 extensibility of C# 550 564 ToString 572 try block 554. 572 exception 550 memory exhaustion 552 standardized exception handling exception base class 551 memory leak 564 553 exception can terminate program Message 561. Andrew 551 run-time exceptions 564 eliminate resource leaks 564 enclosing try block 562 L error detected in a constructor 562 S library classes 553 Error handling code 550 stack 556. 557. 555. 555. All Rights Reserved. 555. 554. 569 IOException 563 554 disk I/O completion 552 resumption model of exception division by zero 557. 562 P polymorphic processing of related C errors 563 call stack 569. 569. mission-critical computing 561 System. 564 inheriting from exception class client of a library 553 release resources acquired in a 572 conventional error handling try block 555 InnerException 572 techniques 552 resource leak 553. 561 I catch handler for a group of IndexOutOfRangeExcep- exceptions 556 tion 555. 569 M StackTrace 569. 564 program’s fault tolerance 551 561. 570 error-processing code 551 stack trace message 571 Exception 551. 563 MSDN documentation 558 SystemException 564 exception not caught in a console application 554 exception not caught in a N T Windows application 554 negative infinity 558 termination model of exception exception object 555 network message arrival 552 handling 554 exception occurs in an exception no handler found for an exception throw an exception 553. 558 handling 554 K rethrow an exception 557. 564 F O try completing successfully 567 fault-tolerant programs 550 object to be thrown 555 type of the thrown exception 554 © Copyright 1992–2002 by Deitel & Associates. 564 publicly released products 550 catch handler 555. asynchronous events 552 finally block typically 564 contains code to release overflow 552 B resources 564 business-critical computing 561 FormatException 557. 556. 570. 556. 560 execution stack 552. 564 input/output 563 Int32.Parse 560 resource-release code 565 D invalid array subscript 555 result of an uncaught exception default exception handler 554. Bjarne 551 execution 555 method call stack 569. 556. 7/2/01 . handler 557 556 555. 561 E Koenig. 552. 565 keyboard input problems 552 robust applications 550. 554. 564 out-of-range array subscript 552. 561.Exception 555 561. 554. Inc.Index 1 A file processing 563 object-oriented programming 551 finalize method 562 on-line documentation 562 arithmetic overflow 552 finally block 554. 560. 564 R catch( Exception e ) 556 reference counts 561 inheritance with exceptions 563 catch-all handler 557 release resources 555. garbage collection 561.

7/2/01 . 556 © Copyright 1992–2002 by Deitel & Associates.2 Index U uncaught exception 551. Inc. All Rights Reserved.