Presentation is loading. Please wait.

Presentation is loading. Please wait.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 8 Exceptions and Assertions.

Similar presentations


Presentation on theme: "©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 8 Exceptions and Assertions."— Presentation transcript:

1 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 8 Exceptions and Assertions

2 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 8 Objectives After you have read and studied this chapter, you should be able to Improve the reliability of code by incorporating exception-handling and assertion routines. Write methods that propagate exceptions. Implement catch-try blocks for catching and handling thrown exceptions.

3 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 8 Objectives After you have read and studied this chapter, you should be able to Write programmer-defined exception classes. Distinguish between checked and unchecked, or runtime, exceptions. Use assertions in methods to increase the chance of detecting bugs during development. Construct a program using the supervisor- subordinate design pattern.

4 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 8.1 Catching Exceptions An exception represents an error condition that can occur during the normal course of program execution. When an exception occurs, or is thrown, the normal sequence of flow is terminated. The exception-handling routine is then executed; we say the thrown exception is caught.

5 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 8.1 Catching Exceptions We can increase our programs’ reliability and robustness if we catch the exceptions ourselves using error recovery routines we develop. One way to do this is to wrap the statements that may throw an exception with the try-catch control statement.

6 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 8.1 Catching Exceptions inputStr = JOptionPane.showInputDialog(null, prompt); try { age = Integer.parseInt(inputStr); } catch (NumberFormatException e){ JOptionPane.showMessageDialog(null, “’” + inputStr +‘ is invalid\n” +“Please enter digits only”);

7 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 8.1 Catching Exceptions Statements in the try block are executed in sequence. When one of the statements throws an exception, control is passed to the matching catch block and statements inside the catch block are executed.

8 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 8.1 Catching Exceptions The execution then continues to the statement following the try-block statement, ignoring any remaining statements in the try block. If no statements in the try block throw an exception, the catch block is ignored. Execution continues with the statement following the try-catch statement.

9 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig. 8.1 Two control flows of the try-catch statement with one catch block.

10 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 8.1 Catching Exceptions We must specify which exception we are catching in the catch block’s parameter list. In Java an exception is represented as an instance of the Throwable class or its subclasses. The Throwable class has two subclasses: Error Exception

11 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 8.1 Catching Exceptions The Error class represents serious problems that should not be caught by ordinary applications. The Exception class represents error conditions that should be caught.

12 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 8.1 Catching Exceptions There are two methods of the Throwable class we can call to get information about the thrown exception: getMessage printStackTrace

13 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 8.2 Throwing Exceptions An exception is thrown using the throw statement. throw where is an instance of the Throwable class or its subclasses.

14 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 8.2 Throwing Exceptions When there are multiple catch blocks in a try-catch statement, they are checked in sequence. It is important to check more specialized exception classes before the more general exception classes. When an exception is thrown, its matching catch block is executed and the other catch blocks are ignored.

15 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig. 8.2 Two possible control flows of the try- catch statement with multiple catch blocks.

16 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 8.2 Throwing Exceptions If none of the catch blocks matches the thrown exception, the system will search down the stack trace for a method with a matching catch block. If none is found, the system will handle the thrown exception.

17 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 8.2 Throwing Exceptions If there is a block of code that must be executed regardless of whether an exception is thrown, we use the reserved word finally. inputStr = JOptionPane.showInputDialog(null, “”); try{ number = Integer.parseInt(inputStr); if (num>100) { throw new Exception(“Out of bound”); } } catch (NumberFormatException e) { System.out.println(“Cannot convert to int”); } catch (Exception e) { System.out.println(“Error: ” + e.getMessage()); } finally { System.out.println(“DONE”); }

18 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 8.2 Throwing Exceptions Even if there is a return statement inside the try block, the finally block is executed. When the return statement is encountered in the try block, statements in the finally block are executed before actually returning from the method.

19 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig. 8.3 Two possible control flows of the try- catch statement with multiple catch blocks and the finally block.

20 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 8.3 Propagating Exceptions When a method may throw an exception, either directly or indirectly, we call the method an exception thrower. Every exception thrower must be one of two types: catcher. propagator.

21 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 8.3 Propagating Exceptions An exception catcher is an exception thrower that includes a matching catch block for the thrown exception. An exception propagator does not contain a matching catch block. A method may be a catcher of one exception and a propagator of another.

22 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig. 8.4 Figure 8.4, which follows, shows a sequence of method calls among the exception throwers. Method D throws an instance of Exception. The green arrows indicate the direction of calls. The red arrows show the reversing of call sequence, looking for a matching catcher. Method B is the catcher. The call sequence is traced by using a stack.

23 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig. 8.4

24 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 8.3 Propagating Exceptions If a method is an exception propagator, we need to modify its header to declare the type of exceptions the method propagates. We use the reserved word throws for this declaration. void C( ) throws Exception {... } void D( ) throws Exception {... }

25 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 8.3 Propagating Exceptions Without the required throws Exception clause, the program will not compile. However, for the exception of the type called runtime exceptions, the throws clause is optional.

26 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 8.3 Propagating Exceptions Do not catch an exception that is thrown as a result of violating a condition set by the client programmer. Instead, propagate the exception back to the client programmer’s code and let him or her handle it.

27 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 8.3 Propagating Exceptions The following class, AgeInputVer4, allows client programmers to specify the lower and upper bounds of acceptable input values. /* Chapter 8 Sample Class: Class to input age File: AgeInputVer4.java */ import javax.swing.*; class AgeInputVer4 { /** Default prompt message */ private static final String DEFAULT_MESSAGE = "Your age:";

28 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 8.3 Propagating Exceptions /** Default constant for the age lower bound */ private static final int DEFAULT_LOWER_BOUND = 0; /** Default constant for the age upper bound */ private static final int DEFAULT_UPPER_BOUND = 99; /** Age lower bound */ private int lowerBound; /** Age upper bound */ private int upperBound; /** * Default constructor */ public AgeInputVer4( ) throws IllegalArgumentException { setBounds(DEFAULT_LOWER_BOUND, DEFAULT_UPPER_BOUND); }

29 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 8.3 Propagating Exceptions /** * Constructs an age input with the specified lower * and upper bounds. * low the lower bound of acceptable input values high the upper bound of acceptable input values */ public AgeInputVer4(int low, int high) throws IllegalArgumentException { if (low > high) { throw new IllegalArgumentException( "Low (" + low + ") was " + "larger than high(" + high + ")"); } else { setBounds(low, high); }

30 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 8.3 Propagating Exceptions /** * Inputs the age from an input dialog with * default prompt */ public int getAge() throws Exception { return getAge(DEFAULT_MESSAGE); } /** * Inputs the age from an input dialog with * the designated prompt * prompt message to prompt the user */ public int getAge(String prompt)throws Exception { String inputStr; int age;

31 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 8.3 Propagating Exceptions while (true) { inputStr = JOptionPane.showInputDialog(null, prompt); try { age = Integer.parseInt(inputStr); if (age upperBound) { throw new Exception("Input out of bound"); } return age; //input okay so return the value //& exit } catch (NumberFormatException e) { JOptionPane.showMessageDialog(null, "'" + inputStr + "' is invalid\n" + "Please enter digits only"); }

32 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 8.3 Propagating Exceptions /** * Sets the lower and upper bounds of the input * low the lower bound of acceptable input values high the upper bound of acceptable input values */ private void setBounds(int low, int high) { lowerBound = low; upperBound = high; }

33 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 8.4 Types of Exceptions All types of thrown errors are instances of the Throwable class or its subclasses. Serious errors are represented by instances of the Error class or its subclasses. Exceptional cases that common applications should handle are represented by instances of the Exception class or its subclasses.

34 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig. 8.5 Some classes in the inheritance hierarchy from the Throwable class. There are over 60 classes in the hierarchy.

35 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 8.4 Types of Exceptions There are two types of exceptions: Checked. Unchecked. A checked exception is an exception that is checked at compile time. All other exceptions are unchecked, or runtime, exceptions. As the name suggests, they are detected only at runtime.

36 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 8.4 Types of Exceptions If a method is a propagator of checked exceptions, the method must have the throws clause. When calling a method that can throw checked exceptions, use the try-catch statement and place the call in the try block, or modify the method header to include the appropriate throws clause.

37 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 8.4 Types of Exceptions If a method is a propagator of runtime exceptions or errors, the throws clause is optional.

38 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig. 8.6 Callers of a method that can throw a checked exception must include the try- catch statement in the method body or the throws clause in the header.

39 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig. 8.7 It is optional for callers of a method that can throw runtime exceptions to include the try- catch statement in the method body or the throws clause in the header.

40 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 8.5 Programmer-Defined Exceptions Instead of using generic exception classes, we can define our own exception classes and attach useful information to the exception objects. When creating a new customized exception class, define it as a checked exception to ensure client programmers handle thrown exceptions of this class in their code.

41 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 8.6 Assertions The new assertion feature is available only from Java 2 SDK 1.4. Be sure to use the right version when compiling and running programs with assertions.

42 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 8.6 Assertions The syntax for the assert statement is assert ; where represents the condition that must be true if the code is working correctly. If the expression results in false, an AssertionError (a subclass of Error) is thrown.

43 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 8.6 Assertions For example: public double fromDollar(double dollar){ assert exchangeRate > 0.0; return (dollar * exchangeRate); } public double toDollar(double foreignMoney){ assert exchangeRate > 0.0; return (foreignMoney / exchangeRate); }

44 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 8.6 Assertions The assert statement may also take the form: assert : ; where represents the value passed as an argument to the constructor of the AssertionError class. The value serves as the detailed message of a thrown error.

45 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 8.6 Assertions For example: public double fromDollar(double dollar){ assert exchangeRate > 0.0: “Exchange rate = “ + exchangeRate + “.\nIt must be a positive value.”; return (dollar * exchangeRate); }

46 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 8.6 Assertions Before Java 2 SDK 1.4, the word assert is a valid nonreserved identifier. In version 1.4, the word assert is treated as a regular identifier to ensure compatibility. To enable the assertion mechanism, compile the source file using javac –source 1.4

47 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 8.6 Assertions To run the program with assertions enabled, use java –ea If the –ea option is not provided, the program is executed without checking assertions.

48 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 8.6 Assertions Do not use the assertion feature to ensure the validity of an argument. Use assertions to detect internal programming errors, and use exceptions to notify client programmers of the misuse of classes.

49 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 8.6 Assertions Precondition assertions check for a condition that must be true before executing a method. Postcondition assertions check conditions that must be true after a method is executed. A control-flow invariant is a third type of assertion, under which control must flow to one of a number of particular cases.

50 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 8.7 Supervisor-Subordinate Design Pattern In a client-service design model, the client calls the method of a service object, and the service object carries out the requested operation. The supervisor-subordinate design pattern is similar to, but more sophisticated than, the client-service model.

51 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 8.7 Supervisor-Subordinate Design Pattern In the supervisor-subordinate design pattern, the supervisor object controls a subordinate object, but the subordinate can also call the supervisor’s method.

52 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 8.7 Supervisor-Subordinate Design Pattern To implement this design pattern, we must establish mutual references between the supervisor and subordinate.

53 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 8.7 Supervisor-Subordinate Design Pattern For example: class Supervisor { private Subordinate worker; public Supervisor ( ) {... worker = new Subordinate(this);... }... } class Subordinate { private Supervisor boss; public Subordinate(Supervisor boss) {... this.boss = boss;... }... }

54 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 8.7 Supervisor-Subordinate Design Pattern When a new supervisor object is created, the subordinate is created also, and the mutual references are established as follows:


Download ppt "©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 8 Exceptions and Assertions."

Similar presentations


Ads by Google