Presentation is loading. Please wait.

Presentation is loading. Please wait.

 2009 Pearson Education, Inc. All rights reserved. 1 13 Exception Handling.

Similar presentations


Presentation on theme: " 2009 Pearson Education, Inc. All rights reserved. 1 13 Exception Handling."— Presentation transcript:

1  2009 Pearson Education, Inc. All rights reserved. 1 13 Exception Handling

2  2009 Pearson Education, Inc. All rights reserved. 2 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. – J. D. Salinger

3  2009 Pearson Education, Inc. All rights reserved. 3 And oftentimes excusing of a fault Doth make the fault the worse by the excuse. – William Shakespeare O infinite virtue! com’st thou smiling from the world’s great snare uncaught? – William Shakespeare

4  2009 Pearson Education, Inc. All rights reserved. 4 OBJECTIVES In this chapter you will learn:  What exceptions are and how they are handled.  When to use exception handling.  To use try blocks to delimit code in which exceptions might occur.  To throw exceptions to indicate a problem.  To use catch blocks to specify exception handlers.  To use the finally block to release resources.  The.NET exception class hierarchy.  Exception properties.  To create user-defined exceptions.

5  2009 Pearson Education, Inc. All rights reserved. 5 13.1 Introduction 13.2 Exception Handling Overview 13.3 Example: Divide by Zero without Exception Handling 13.4 Example: Handling DivideByZeroException s and FormatException s 13.5.NET Exception Hierarchy 13.6 finally Block 13.7 Exception Properties 13.8 User-Defined Exception Classes

6  2009 Pearson Education, Inc. All rights reserved. 6 13.1 Introduction An exception is an indication of a problem that occurs during a program’s execution. Exception handling enables applications to resolve exceptions. Exception handling enables clear, robust and more fault-tolerant programs. Error-Prevention Tip 13.1 Exception handling helps improve a program’s fault tolerance.

7  2009 Pearson Education, Inc. All rights reserved. 7 13.2 Exception Handling Overview Consider the following pseudocode: Perform a task If the preceding task did not execute correctly Perform error processing Perform next task If the preceding task did not execute correctly Perform error processing … In this pseudocode, we begin by performing a task; then we test whether that task executed correctly. If not, we perform error processing.

8  2009 Pearson Education, Inc. All rights reserved. 8 13.2 Exception Handling Overview (Cont.) Exception handling enables programmers to remove error-handling code from the “main line” of the program’s execution. Programmers can decide to handle all exceptions, all exceptions of a certain type or all exceptions of related types. Such flexibility reduces the likelihood that errors will be overlooked.

9  2009 Pearson Education, Inc. All rights reserved. 9 Fig. 13.1 | Integer division without exception handling. (Part 1 of 3.) Outline DivideByZeroNo ExceptionHandling.cs ( 1 of 3 ) Figure 13.1’s application divides one input integer by a second to obtain an int result. In this example, we’ll see that an exception is thrown when a method detects a problem. Converting values can cause a FormatException.

10  2009 Pearson Education, Inc. All rights reserved. 10 Outline Division can cause a DivideByZeroException. DivideByZeroNo ExceptionHandling.cs ( 2 of 3 ) Fig. 13.1 | Integer division without exception handling. (Part 2 of 3.)

11  2009 Pearson Education, Inc. All rights reserved. 11 Outline DivideByZeroNo ExceptionHandling.cs ( 3 of 3 ) Fig. 13.1 | Integer division without exception handling. (Part 3 of 3.)

12  2009 Pearson Education, Inc. All rights reserved. 12 13.3 Example: Divide by Zero without Exception Handling If you run using Debug > Start Debugging, the program pauses at the line where an exception occurs. Try executing the application from a Command Prompt window. When an error arises, a dialog indicates that the application has encountered a problem and needs to close. An error message describing the problem is displayed in the Command Prompt.

13  2009 Pearson Education, Inc. All rights reserved. 13 13.3 Example: Divide by Zero without Exception Handling (Cont.) Additional information — known as a stack trace — displays the exception name and the path of execution that led to the exception. Each “ at ” line in the stack trace indicates a line of code in the particular method that was executing when the exception occurred. This information tells where the exception originated, and what method calls were made to get to that point.

14  2009 Pearson Education, Inc. All rights reserved. 14 13.3 Example: Divide by Zero without Exception Handling (Cont.) A FormatException occurs when Convert method ToInt32 receives a string that does not represent a valid integer. A program may continue executing even though an exception has occurred and a stack trace has been printed. In such cases, the application may produce incorrect results.

15  2009 Pearson Education, Inc. All rights reserved. 15 This application (Fig. 13.2) uses exception handling to process DivideByZeroException s and FormatException s. This program demonstrates how to catch and handle (i.e., deal with) such exceptions. Outline DivideByZeroTest.cs ( 1 of 4 ) Fig. 13.2 | FormatException and DivideByZeroException handlers. (Part 1 of 4.)

16  2009 Pearson Education, Inc. All rights reserved. 16 Outline DivideByZeroTest.cs ( 2 of 4 ) Fig. 13.2 | FormatException and DivideByZeroException handlers. (Part 2 of 4.)

17  2009 Pearson Education, Inc. All rights reserved. 17 Outline DivideByZeroTest.cs ( 3 of 4 ) Fig. 13.2 | FormatException and DivideByZeroException handlers. (Part 3 of 4.) This block catches and handles a FormatException. This block catches and handles a DivideBy- ZeroException.

18  2009 Pearson Education, Inc. All rights reserved. 18 Outline a) Performing integer division b) Dividing by zero d) Entering a string value e) Error message c) Error message DivideByZeroTest.cs ( 4 of 4 ) Fig. 13.2 | FormatException and DivideByZeroException handlers. (Part 3 of 4.)

19  2009 Pearson Education, Inc. All rights reserved. 19 13.4 Example: Handling DivideByZeroExceptions and FormatExceptions The Int32.TryParse method converts a string to an int value if possible. The method requires two arguments — one is the string to parse and the other is the variable in which the converted value is to be stored. The method returns true if the string was parsed successfully. If the string could not be converted, the value 0 is assigned to the second argument.

20  2009 Pearson Education, Inc. All rights reserved. 20 13.4 Example: Handling DivideByZeroExceptions and FormatExceptions (Cont.) 13.4.1 Enclosing Code in a try Block A try block encloses code that might throw exceptions and code that is skipped when an exception occurs.

21  2009 Pearson Education, Inc. All rights reserved. 21 13.4 Example: Handling DivideByZeroExceptions and FormatExceptions (Cont.) 13.4.2 Catching Exceptions When an exception occurs in a try block, a corresponding catch block catches the exception and handles it. At least one catch block must immediately follow a try block. A catch block specifies an exception parameter representing the exception that the catch block can handle. Optionally, you can include a catch block that does not specify an exception type to catch all exception types.

22  2009 Pearson Education, Inc. All rights reserved. 22 13.4 Example: Handling DivideByZeroExceptions and FormatExceptions (Cont.) 13.4.3 Uncaught Exceptions An uncaught exception (or unhandled exception) is an exception for which there is no matching catch block. If you run the application from Visual Studio with debugging, a window called the Exception Assistant (Fig. 13.3) appears.

23  2009 Pearson Education, Inc. All rights reserved. 23 13.4 Example: Handling DivideByZeroExceptions and FormatExceptions (Cont.) Throw pointException Assistant Fig. 13.3 | Exception Assistant.

24  2009 Pearson Education, Inc. All rights reserved. 24 13.4 Example: Handling DivideByZeroExceptions and FormatExceptions (Cont.) 13.4.4 Termination Model of Exception Handling When a method called in a program or the CLR detects a problem, the method or the CLR throws an exception. The point at which an exception occurs is called the throw point If an exception occurs in a try block, program control immediately transfers to the first catch block matching the type of the thrown exception. After the exception is handled, program control resumes after the last catch block. This is known as the termination model of exception handling.

25  2009 Pearson Education, Inc. All rights reserved. 25 13.4 Example: Handling DivideByZeroExceptions and FormatExceptions (Cont.) Common Programming Error 13.1 Logic errors can occur if you assume that after an exception is handled, control will return to the first statement after the throw point. Common Programming Error 13.2 Specifying a comma-separated list of parameters in a catch block is a syntax error. A catch block can have at most one parameter.

26  2009 Pearson Education, Inc. All rights reserved. 26 13.5.NET Exception Hierarchy In C#, only objects of class Exception and its derived classes may be thrown and caught. Exceptions thrown in other.NET languages can be caught with the general catch clause.

27  2009 Pearson Education, Inc. All rights reserved. 27 13.5.NET Exception Hierarchy (Cont.) 13.5.1 Class SystemException Class Exception is the base class of.NET ’ s exception class hierarchy. The CLR generates SystemExceptions, derived from class Exception, which can occur at any point during program execution. If a program attempts to access an out-of-range array index, the CLR throws an exception of type IndexOutOfRangeException. Attempting to use a null reference causes a NullReferenceException.

28  2009 Pearson Education, Inc. All rights reserved. 28 13.5.NET Exception Hierarchy (Cont.) A catch block can use a base-class type to catch a hierarchy of related exceptions. A catch block that specifies a parameter of type Exception can catch all exceptions. This technique makes sense only if the handling behavior is the same for a base class and all derived classes. Common Programming Error 13.3 The compiler issues an error if a catch block that catches a base- class exception is placed before a catch block for any of that class’s derived-class types. In this case, the base-class catch block would catch all base-class and derived-class exceptions, so the derived-class exception handler would never execute—a possible logic error.

29  2009 Pearson Education, Inc. All rights reserved. 29 13.5.NET Exception Hierarchy (Cont.) 13.5.2 Determining Which Exceptions a Method Throws Search for “ Convert.ToInt32 method ” in the Index of the Visual Studio online documentation. Select the document entitled Convert.ToInt32 Method ( System ). In the document that describes the method, click the link ToInt32(String ). The Exceptions section indicates that method Convert.ToInt32 throws two exception types.

30  2009 Pearson Education, Inc. All rights reserved. 30 13.5.NET Exception Hierarchy (Cont.) Software Engineering Observation 13.1 If a method throws exceptions, statements that invoke the method directly or indirectly should be placed in try blocks, and those exceptions should be caught and handled.

31  2009 Pearson Education, Inc. All rights reserved. 31 13.6 finally Block Programs frequently request and release resources dynamically. Operating systems typically prevent more than one program from manipulating a file. Therefore, the program should close the file (i.e., release the resource) so other programs can use it. If the file is not closed, a resource leak occurs.

32  2009 Pearson Education, Inc. All rights reserved. 32 Error-Prevention Tip 13.2 The CLR does not completely eliminate memory leaks. The CLR will not garbage collect an object until the program contains no more references to that object and even then there may be a delay until the memory is required. Thus, memory leaks can occur if programmers inadvertently keep references to unwanted objects. 13.6 finally Block (Cont.)

33  2009 Pearson Education, Inc. All rights reserved. 33 13.6 finally Block (Cont.) Exceptions often occur while processing resources. Regardless of whether a program experiences exceptions, the program should close the file when it is no longer needed. C# provides the finally block, which is guaranteed to execute regardless of whether an exception occurs. This makes the finally block ideal to release resources from the corresponding try block.

34  2009 Pearson Education, Inc. All rights reserved. 34 13.6 finally Block (Cont.) Local variables in a try block cannot be accessed in the corresponding finally block, so variables that must be accessed in both should be declared before the try block. Error-Prevention Tip 13.3 A finally block typically contains code to release resources acquired in the corresponding try block, which makes the finally block an effective mechanism for eliminating resource leaks.

35  2009 Pearson Education, Inc. All rights reserved. 35 13.6 finally Block (Cont.) Performance Tip 13.1 As a rule, resources should be released as soon as they are no longer needed in a program. This makes them available for reuse promptly. Common Programming Error 13.4 Placing the finally block before a catch block is a syntax error.

36  2009 Pearson Education, Inc. All rights reserved. 36 Outline UsingExceptions.cs ( 1 of 10 ) The application in Fig. 13.4 demonstrates that the finally block always executes. Main invokes method DoesNotThrowException. Main invokes method ThrowExceptionWithCatch. Fig. 13.4 | finally blocks always execute, even when no exception occurs. (Part 1 of 8.)

37  2009 Pearson Education, Inc. All rights reserved. 37 Outline UsingExceptions.cs ( 2 of 10 ) Fig. 13.4 | finally blocks always execute, even when no exception occurs. (Part 2 of 8.)

38  2009 Pearson Education, Inc. All rights reserved. 38 Outline Because the try block does not throw any exceptions, the catch block is ignored. UsingExceptions.cs ( 3 of 10 ) Fig. 13.4 | finally blocks always execute, even when no exception occurs. (Part 3 of 8.)

39  2009 Pearson Education, Inc. All rights reserved. 39 Outline The finally block always executes. The try block throws an exception. The catch and finally blocks execute when the exception occurs. UsingExceptions.cs ( 4 of 10 ) Fig. 13.4 | finally blocks always execute, even when no exception occurs. (Part 4 of 8.)

40  2009 Pearson Education, Inc. All rights reserved. 40 Outline The catch and finally blocks execute when the exception occurs. The try block throws an exception. UsingExceptions.cs ( 5 of 10 ) Fig. 13.4 | finally blocks always execute, even when no exception occurs. (Part 5 of 8.)

41  2009 Pearson Education, Inc. All rights reserved. 41 Outline The finally block executes but the exception remains uncaught until after control returns to Main. The try block throws an exception. UsingExceptions.cs ( 6 of 10 ) Fig. 13.4 | finally blocks always execute, even when no exception occurs. (Part 6 of 8.)

42  2009 Pearson Education, Inc. All rights reserved. 42 Outline The catch block rethrows the exception, which is then caught after control returns to Main. The catch and finally blocks execute when the exception occurs. UsingExceptions.cs ( 7 of 10 ) Fig. 13.4 | finally blocks always execute, even when no exception occurs. (Part 7 of 8.)

43  2009 Pearson Education, Inc. All rights reserved. 43 Fig. 13.4 | finally blocks always execute, even when no exception occurs. (Part 8 of 8.)

44  2009 Pearson Education, Inc. All rights reserved. 44 Common Programming Error 13.5 It is a compilation error if the argument of a throw —an exception object—is not of class Exception or one of its derived classes. Common Programming Error 13.6 Throwing an exception from a finally block can be dangerous. If an uncaught exception is awaiting processing when the finally block executes, and the finally block throws a new exception that is not caught in the finally block, the first exception is lost, and the new exception is passed to the next enclosing try block.

45  2009 Pearson Education, Inc. All rights reserved. 45 Error-Prevention Tip 13.4 When placing code that can throw an exception in a finally block, always enclose the code in a try statement that catches the appropriate exception types. This prevents the loss of any uncaught and rethrown exceptions that occur before the finally block executes. Software Engineering Observation 13.2 Do not place try blocks around every statement that might throw an exception—this can make programs difficult to read. It’s better to place one try block around a significant portion of code, and follow this try block with catch blocks that handle each possible exception. Then follow the catch blocks with a single finally block. Separate try blocks should be used when it is important to distinguish between multiple statements that can throw the same exception type.

46  2009 Pearson Education, Inc. All rights reserved. 46 13.6 finally Block (Cont.) The using statement simplifies writing code in which you obtain a resource. The general form of a using statement is: using ( ExampleObject e = new ExampleObject() ) { e.SomeMethod(); }

47  2009 Pearson Education, Inc. All rights reserved. 47 13.6 finally Block (Cont.) The using statement code is equivalent to { ExampleObject e = new ExampleObject(); try { e.SomeMethod(); } finally { if ( e != null ) ( ( IDisposable ) e ).Dispose(); } }

48  2009 Pearson Education, Inc. All rights reserved. 48 13.7 Exception Properties Class Exception ’s properties are used to formulate error messages indicating a caught exception. – Property Message stores the error message associated with an Exception object. – Property StackTrace contains a string that represents the method-call stack.

49  2009 Pearson Education, Inc. All rights reserved. 49 13.7 Exception Properties (Cont.) Error-Prevention Tip 13.5 If the program database (PDB) file that contains the debugging information for a method is accessible to the IDE, the stack trace also includes line numbers; the first line number indicates the throw point, and subsequent line numbers indicate the locations from which the methods in the stack trace were called. PDB files are created by the IDE to maintain the debugging information for your projects.

50  2009 Pearson Education, Inc. All rights reserved. 50 13.7 Exception Properties (Cont.) When an exception occurs, a programmer might use a different error message or indicate a new exception type. The original exception object is stored in the InnerException property.

51  2009 Pearson Education, Inc. All rights reserved. 51 13.7 Exception Properties (Cont.) Class Exception provides other properties: – HelpLink specifies the location of a help file that describes the problem. – Source specifies the name of the application or object that caused the exception. – TargetSite specifies the method where the exception originated.

52  2009 Pearson Education, Inc. All rights reserved. 52 Outline Our next example (Fig. 13.5) demonstrates properties of class Exception. Properties.cs ( 1 of 5 ) Fig. 13.5 | Stack unwinding and Exception class properties. (Part 1 of 5.)

53  2009 Pearson Education, Inc. All rights reserved. 53 Outline Outputting properties of class Exception. Method1 and Method2 are added to the method stack, and then unwind when they do not catch Method3 ’s exception. Properties.cs ( 2 of 5 ) Fig. 13.5 | Stack unwinding and Exception class properties. (Part 2 of 5.)

54  2009 Pearson Education, Inc. All rights reserved. 54 Outline Method1 and Method2 are added to the method stack, and then unwind when they do not catch Method3 ’s exception. Method3 catches then rethrows the exception. Properties.cs ( 3 of 5 ) Fig. 13.5 | Stack unwinding and Exception class properties. (Part 3 of 5.)

55  2009 Pearson Education, Inc. All rights reserved. 55 Outline Properties.cs ( 4 of 5 ) Fig. 13.5 | Stack unwinding and Exception class properties. (Part 4 of 5.)

56  2009 Pearson Education, Inc. All rights reserved. 56 Outline Properties.cs ( 5 of 5 ) Fig. 13.5 | Stack unwinding and Exception class properties. (Part 5 of 5.)

57  2009 Pearson Education, Inc. All rights reserved. 57 13.7 Exception Properties (Cont.) The method called most recently appears at the top of the stack; the first method ( Main ) appears at the bottom. The StackTrace represents the state of the method-call stack at the throw point. The inner-exception information includes the inner exception stack trace. Error-Prevention Tip 13.6 When catching and rethrowing an exception, provide additional debugging information in the rethrown exception. To do so, create an Exception object containing more specific debugging information, then pass the original caught exception to the new exception object’s constructor to initialize the InnerException property.

58  2009 Pearson Education, Inc. All rights reserved. 58 13.8 User-Defined Exception Classes In some cases, you might create exception classes specific to the problems that occur in your programs. User-defined exception classes should derive directly or indirectly from class Exception of namespace System. Exceptions should be documented so that other developers will know how to handle them.

59  2009 Pearson Education, Inc. All rights reserved. 59 13.8 User-Defined Exception Classes (Cont.) User-defined exceptions should define three constructors: – a parameterless constructor – a constructor that receives a string argument (the error message) – a constructor that receives a string argument and an Exception argument (the error message and the inner exception object)

60  2009 Pearson Education, Inc. All rights reserved. 60 Good Programming Practice 13.1 Associating each type of malfunction with an appropriately named exception class improves program clarity. Software Engineering Observation 13.3 Before creating a user-defined exception class, investigate the existing exceptions in the.NET Framework Class Library to determine whether an appropriate exception type already exists. 13.8 User-Defined Exception Classes (Cont.)

61  2009 Pearson Education, Inc. All rights reserved. 61 Outline NegativeNumber Exception.cs ( 1 of 2 ) Class NegativeNumberException (Fig. 13.6) represents exceptions that occur when a program performs an illegal operation on a negative number. Inheriting from class Exception. Parameterless constructor. Fig. 13.6 | NegativeNumberException represents exceptions caused by illegal operations performed on negative numbers. (Part 1 of 2.)

62  2009 Pearson Education, Inc. All rights reserved. 62 Outline Constructor with a single argument (the Message ). Constructor with two arguments (the Message and InnerException ). Fig. 13.6 | NegativeNumberException represents exceptions caused by illegal operations performed on negative numbers. (Part 2 of 2.) NegativeNumber Exception.cs ( 2 of 2 )

63  2009 Pearson Education, Inc. All rights reserved. 63 Outline SquareRootTest.cs ( 1 of 4 ) Class SquareRootForm (Fig. 13.7) demonstrates our user-defined exception class. Fig. 13.7 | Demonstrating a user-defined exception class. (Part 1 of 4.)

64  2009 Pearson Education, Inc. All rights reserved. 64 Outline SquareRootTest.cs ( 2 of 4 ) If the numeric value that the user enters is negative, SquareRoot throws a NegativeNumber- Exception. SquareRoot invokes Math ’s Sqrt method. Fig. 13.7 | Demonstrating a user-defined exception class. (Part 2 of 4.)

65  2009 Pearson Education, Inc. All rights reserved. 65 Outline SquareRootTest.cs ( 3 of 4 ) Catching and handling a NegativeNumber­ Exception. Fig. 13.7 | Demonstrating a user-defined exception class. (Part 3 of 4.)

66  2009 Pearson Education, Inc. All rights reserved. 66 Outline SquareRootTest.cs ( 4 of 4 ) a) Calculating an integer square root c) Attempting a negative square rootd) Error message displayed b) Calculating a double square root Fig. 13.7 | Demonstrating a user-defined exception class. (Part 4 of 4.)


Download ppt " 2009 Pearson Education, Inc. All rights reserved. 1 13 Exception Handling."

Similar presentations


Ads by Google