Presentation is loading. Please wait.

Presentation is loading. Please wait.

 2006 Pearson Education, Inc. All rights reserved. 1 12 Exception Handling.

Similar presentations


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

1  2006 Pearson Education, Inc. All rights reserved. 1 12 Exception Handling

2  2006 Pearson Education, Inc. All rights reserved. 2 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

3  2006 Pearson Education, Inc. All rights reserved. 3 And oftentimes excusing of a fault Doth make the fault the worse by the excuse. — 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 O infinite virtue! com’st thou smiling from the world’s great snare uncaught? — William Shakespeare

4  2006 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  2006 Pearson Education, Inc. All rights reserved. 5 12.1 Introduction 12.2 Exception Handling Overview 12.3 Example: Divide by Zero Without Exception Handling 12.4 Example: Handling DivideByZeroException s and FormatException s 12.4.1 Enclosing Code in a try Block 12.4.2 Catching Exceptions 12.4.3 Uncaught Exceptions 12.4.4 Termination Model of Exception Handling 12.4.5 Flow of Control When Exceptions Occur 12.5.NET Exception Hierarchy 12.5.1 Classes ApplicationException and SystemException 12.5.2 Determining Which Exceptions a Method Throws 12.6 finally Block 12.7 Exception Properties 12.8 User-Defined Exception Classes 12.9 Wrap-Up

6  2006 Pearson Education, Inc. All rights reserved. 6 12.1 Introduction Exception – An indication of a problem that occurs during a program’s execution – System.Exception is the base class for all exceptions Exception handling – Resolving exceptions that may occur so program can continue or terminate gracefully – Exception handling enables programmers to create programs that are more robust and fault-tolerant

7  2006 Pearson Education, Inc. All rights reserved. 7 Error-Prevention Tip 12.1 Exception handling helps improve a program’s fault tolerance.

8  2006 Pearson Education, Inc. All rights reserved. 8 12.2 Exception Handling Overview Exception Handling – Intermixing program logic with error-handling logic can make programs difficult to read, modify, maintain and debug – Enables programmers to remove error-handling code from the “main line” of the program’s execution – Improves clarity – Enhances modifiability

9  2006 Pearson Education, Inc. All rights reserved. 9 12.3 Example: Divide By Zero Without Exception Handling Analyzing the Results – Thrown exception An exception that has occurred – Throw point Initial point at which the exception occurs – Stack trace Name of the exception in a descriptive message that indicates the problem – DivideByZeroException Occurs when there is a division by zero – FormatException Occurs when the format of an argument does not meet the parameter specifications of the invoked method

10  2006 Pearson Education, Inc. All rights reserved. 10 Outline DivideByZeroNoExce ptionHandling.cs (1 of 2) Take and assign inputs from user Divide numerator by denominator

11  2006 Pearson Education, Inc. All rights reserved. 11 Outline DivideByZeroNoExce ptionHandling.cs (2 of 2) Exception: division by zero! Exception: denominator is not even a number!

12  2006 Pearson Education, Inc. All rights reserved. 12 12.4 Example: Handling DivideByZeroExceptions and FormatExceptions With exception handling, the program catches and handles (i.e., deals with) the exception Fig. 12.2 displays error message and allows user to enter another set of values

13  2006 Pearson Education, Inc. All rights reserved. 13 Outline DivideByZeroTest.cs (1 of 3)

14  2006 Pearson Education, Inc. All rights reserved. 14 Outline DivideByZeroTest.cs (2 of 3) try block attempts to read input and perform division Retrieve input; FormatException thrown if input are not valid integers DivideByZeroException thrown if the denominator is 0 Catches any FormatException and DivideByZeroException thrown from the try block, respectively Identifier for the DivideByZeroException The property that returns the exception’s corresponding message

15  2006 Pearson Education, Inc. All rights reserved. 15 Outline DivideByZeroTest.cs (3 of 3) (a) (b) (d) (c) (e)

16  2006 Pearson Education, Inc. All rights reserved. 16 12.4.1 Enclosing Code in a try Block try block – Encloses code that might throw an exception and the code that should not execute if an exception occurs – Keyword try followed by a block of code ( { } ) – There must be at least one catch block and/or finally block immediately after the try block try statement – Consists of try block and corresponding catch and/or finally blocks

17  2006 Pearson Education, Inc. All rights reserved. 17 12.4.2 Catching Exceptions catch block – Catches (i.e., receives) and handles an exception – Begins with keyword catch – Exception parameter in parentheses Identifies the exception type and enables catch block to interact with caught exception object If parameter-less, able to catch all exceptions types – Executes when exception of proper type matches

18  2006 Pearson Education, Inc. All rights reserved. 18 12.4.3 Uncaught Exceptions Uncaught exception – There are no matching catch blocks – Program mostly terminates when there is an uncaught exception If debugging in Visual Studio, application pauses and Exception Assistant appears indicating where the exception occured

19  2006 Pearson Education, Inc. All rights reserved. 19 Fig. 12.3 | Exception Assistant. Throw point Exception Assistant

20  2006 Pearson Education, Inc. All rights reserved. 20 12.4.4 Termination Model of Exception Handling When an exception occurs: – try block terminates immediately – Program control transfers to first matching catch block (other catch block(s) are ignored) After exception is handled: – Termination model of exception handling Program control does not return to the throw point because the try block has expired Flow of control proceeds to the first statement after the last catch block – Resumption model of exception handling Program control resumes just after throw point

21  2006 Pearson Education, Inc. All rights reserved. 21 Common Programming Error 12.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.

22  2006 Pearson Education, Inc. All rights reserved. 22 Common Programming Error 12.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.

23  2006 Pearson Education, Inc. All rights reserved. 23 12.5.NET Exception Hierarchy In C#, only objects of class Exception and its derived classes may be thrown or caught

24  2006 Pearson Education, Inc. All rights reserved. 24 12.5.1 Classes ApplicationException and SystemException Class Exception – Can be used to catch all exceptions Catch blocks uses is-a relationship – Derived Class ApplicationException s Base class that programmers can extend to create exception classes specific to their application Programs can recover from most ApplicationException s and continue execution – Derived Class SystemException Mainly, this exception can be avoided if coded properly CLR throws SystemException when it becomes unstable

25  2006 Pearson Education, Inc. All rights reserved. 25 Common Programming Error 12.3 It is a compilation 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. If this were allowed, the base-class catch block would catch all base-class and derived-class exceptions, so the derived-class exception handler would never execute.

26  2006 Pearson Education, Inc. All rights reserved. 26 12.5.2 Determining Which Exceptions a Method Throws Methods in the.NET Framework classes – Read the online documentations (MSDN) – If method throws an exception, its description contains a section called Exceptions

27  2006 Pearson Education, Inc. All rights reserved. 27 Software Engineering Observation 12.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.

28  2006 Pearson Education, Inc. All rights reserved. 28 12.6 finally block Programs that obtain certain resources must return them explicitly to avoid resource leaks finally block – Consists of finally keyword followed by a block of code enclosed in curly braces – Optional in a try statement – Placed after the last catch block (if there is one) – Executes whether or not an exception is thrown in the corresponding try block or any of its corresponding catch blocks – Typically contains resource-release code

29  2006 Pearson Education, Inc. All rights reserved. 29 Error-Prevention Tip 12.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. Thus, memory leaks can occur if programmers inadvertently keep references to unwanted objects.

30  2006 Pearson Education, Inc. All rights reserved. 30 Error-Prevention Tip 12.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.

31  2006 Pearson Education, Inc. All rights reserved. 31 Performance Tip 12.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.

32  2006 Pearson Education, Inc. All rights reserved. 32 Common Programming Error 12.4 Placing the finally block before a catch block is a syntax error.

33  2006 Pearson Education, Inc. All rights reserved. 33 Outline UsingExceptions.cs (1 of 8) No exceptions occur No try block needed, exception handled in method

34  2006 Pearson Education, Inc. All rights reserved. 34 Outline UsingExceptions.cs (2 of 8) Exception handled outside of method Exception handled outside of method; Exception is rethrown

35  2006 Pearson Education, Inc. All rights reserved. 35 Outline UsingExceptions.cs (3 of 8) The finally block executes regardless if there is an exception or not

36  2006 Pearson Education, Inc. All rights reserved. 36 Outline UsingExceptions.cs (4 of 8) The finally block executes regardless if there is an exception or not catch block handles any exceptions Throw exception with personalized message

37  2006 Pearson Education, Inc. All rights reserved. 37 Outline UsingExceptions.cs (5 of 8) The finally block executes regardless if there is an exception or not Exception is thrown and is not caught inside this method

38  2006 Pearson Education, Inc. All rights reserved. 38 Outline UsingExceptions.cs (6 of 8) Throw exception with personalized message Rethrow caught exception

39  2006 Pearson Education, Inc. All rights reserved. 39 Outline UsingExceptions.cs (7 of 8) The finally block executes regardless if there is an exception or not

40  2006 Pearson Education, Inc. All rights reserved. 40 Outline UsingExceptions.cs (8 of 8)

41  2006 Pearson Education, Inc. All rights reserved. 41 12.6 finally block (Cont.) Throwing Exceptions Using the throw statement – throw statement Throw exceptions Keyword throw followed by the exception object Programmers can throw exceptions from a method if something has gone wrong The string passed through the constructor will be the exception object’s error message

42  2006 Pearson Education, Inc. All rights reserved. 42 Common Programming Error 12.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.

43  2006 Pearson Education, Inc. All rights reserved. 43 12.6 finally block (Cont.) Rethrowing Exceptions – Exceptions are rethrown when a catch block decides either that it cannot process the exception or that it can only partially process it – Exception is rethrown by using keyword throw followed by the reference to the exception that was caught

44  2006 Pearson Education, Inc. All rights reserved. 44 12.6 finally block (Cont.) Returning After a finally block – If the try block successfully completes, or if a catch block catches and handles an exception The program continues its execution with the next statement after the finally block – If an exception is not caught, or if a catch block rethrows an exception Program control continues in the next enclosing try block – The enclosing try could be in the calling method or in one of its callers – If a try block executes and has a corresponding finally block The finally block executes even if the try block terminates due to a return statement

45  2006 Pearson Education, Inc. All rights reserved. 45 Common Programming Error 12.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.

46  2006 Pearson Education, Inc. All rights reserved. 46 Error-Prevention Tip 12.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.

47  2006 Pearson Education, Inc. All rights reserved. 47 Software Engineering Observation 12.2 Do not place try blocks around every statement that might throw an exception, because this can make programs difficult to read. It is better to place one try block around a significant portion of code, and follow this try block with catch blocks that handle each of the possible exceptions. 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.

48  2006 Pearson Education, Inc. All rights reserved. 48 12.6 finally block (Cont.) The using Statement – Do not be confused this with the using directive – Simpler way of resource-release code instead of placing in finally block Implicitly places code in try block with corresponding finally block – The resource must be an object that implements IDisposable – Ex: using ( ExampleObject example = new ExampleObject() ) { example.SomeMethod(); }

49  2006 Pearson Education, Inc. All rights reserved. 49 12.7 Exception Properties Exception Properties – Message Stores the error message associated with an Exception object – StackTrace Contains a string that represents the method-call stack

50  2006 Pearson Education, Inc. All rights reserved. 50 Error-Prevention Tip 12.5 A stack trace shows the complete method-call stack at the time an exception occurred. This enables the programmer to view the series of method calls that led to the exception. Information in the stack trace includes the names of the methods on the call stack at the time of the exception, the names of the classes in which the methods are defined and the names of the namespaces in which the classes are defined. If the program database (PDB) file that contains the debugging information for the method is available, 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.

51  2006 Pearson Education, Inc. All rights reserved. 51 12.7 Exception Properties (Cont.) Property InnerException – InnerException Programmers “wrap” exception objects caught in their code so that they then can throw new exception types that are specific to their libraries. If the InnerException property is null, this indicates that the exception was not caused by another exception

52  2006 Pearson Education, Inc. All rights reserved. 52 12.7 Exception Properties (Cont.) Other Exception Properties – HelpLink Specifies location of help file that describe the problem that occurred – Source Specifies the name of the application where the exception occurred – TargetSite Specifies the method where the exception originated

53  2006 Pearson Education, Inc. All rights reserved. 53 12.7 Exception Properties (Cont.) Demonstrating Exception Properties and Stack Unwinding – Stack unwinding When an exception is thrown but not caught in a particular scope (“unwound”) Attempt is made to catch the exception in the outer try block Throwing an Exception with an InnerException – A stack unwinding continues until a catch block catches the exception or the program terminates

54  2006 Pearson Education, Inc. All rights reserved. 54 Outline Properties.cs (1 of 4) Outputs exception type and where it occurred Outputs message associated with the exception object Output the method call stack where the exception initially occurred Output the inner wrapped exception

55  2006 Pearson Education, Inc. All rights reserved. 55 Outline Properties.cs (2 of 4) Call Method2() Call Method3() Generate exception Rewrap and throw exception

56  2006 Pearson Education, Inc. All rights reserved. 56 Outline Properties.cs (3 of 4)

57  2006 Pearson Education, Inc. All rights reserved. 57 Outline Properties.cs (4 of 4)

58  2006 Pearson Education, Inc. All rights reserved. 58 Error-Prevention Tip 12.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.

59  2006 Pearson Education, Inc. All rights reserved. 59 12.8 User-Defined Exception Classes User-defined exception class – Should derive directly or indirectly from class ApplicationException of namespace System – Class name should end with “Exception” – Recommended to have 3 constructors: Constructor that is parameter-less Constructor that takes in a string argument for the error message Constructor that takes in a string and Exception argument for the error message and inner exception object, respectively

60  2006 Pearson Education, Inc. All rights reserved. 60 Good Programming Practice 12.1 Associating each type of malfunction with an appropriately named exception class improves program clarity.

61  2006 Pearson Education, Inc. All rights reserved. 61 Software Engineering Observation 12.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.

62  2006 Pearson Education, Inc. All rights reserved. 62 Outline NegativeNumberExce ption.cs (1 of 2) NegativeNumberException extends ApplicationException Calls the base class constructor with exception message Calls the base class constructor with a string

63  2006 Pearson Education, Inc. All rights reserved. 63 Outline NegativeNumberExce ption.cs (2 of 2) Calls the base class constructor with a string and an Exception

64  2006 Pearson Education, Inc. All rights reserved. 64 Outline SquareRootTest.cs (1 of 3) Throw user defined exception Return square root of the argument

65  2006 Pearson Education, Inc. All rights reserved. 65 Outline SquareRootTest.cs (2 of 3) Notify user of the exception

66  2006 Pearson Education, Inc. All rights reserved. 66 Outline SquareRootTest.cs (3 of 3) (a) (c) (b) (d)


Download ppt " 2006 Pearson Education, Inc. All rights reserved. 1 12 Exception Handling."

Similar presentations


Ads by Google