Tài liệu Bài giảng Chapter 8: Exceptions and Assertions: Chapter 8Exceptions and Assertions©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Chapter 8 ObjectivesAfter you have read and studied this chapter, you should be able toImprove 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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Chapter 8 ObjectivesAfter you have read and studied this chapter, you should be able toWrite 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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.8.1 Catching ExceptionsAn exception represents an error condition that can occur during...
54 trang |
Chia sẻ: honghanh66 | Lượt xem: 1053 | Lượt tải: 0
Bạn đang xem trước 20 trang mẫu tài liệu Bài giảng Chapter 8: Exceptions and Assertions, để tải tài liệu gốc về máy bạn click vào nút DOWNLOAD ở trên
Chapter 8Exceptions and Assertions©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Chapter 8 ObjectivesAfter you have read and studied this chapter, you should be able toImprove 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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Chapter 8 ObjectivesAfter you have read and studied this chapter, you should be able toWrite 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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.8.1 Catching ExceptionsAn 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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.8.1 Catching ExceptionsWe 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. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.8.1 Catching ExceptionsinputStr = JOptionPane.showInputDialog(null, prompt);try {age = Integer.parseInt(inputStr);} catch (NumberFormatException e){ JOptionPane.showMessageDialog(null, “’” + inputStr + ‘ is invalid\n” + “Please enter digits only”);©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.8.1 Catching ExceptionsStatements 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. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.8.1 Catching ExceptionsThe 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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Fig. 8.1Two control flows of the try-catch statement with one catch block. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.8.1 Catching ExceptionsWe 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:ErrorException©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.8.1 Catching ExceptionsThe Error class represents serious problems that should not be caught by ordinary applications.The Exception class represents error conditions that should be caught.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.8.1 Catching ExceptionsThere are two methods of the Throwable class we can call to get information about the thrown exception:getMessageprintStackTrace©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.8.2 Throwing ExceptionsAn exception is thrown using the throw statement.throw where is an instance of the Throwable class or its subclasses.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.8.2 Throwing ExceptionsWhen 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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Fig. 8.2Two possible control flows of the try-catch statement with multiple catch blocks. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.8.2 Throwing ExceptionsIf 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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.8.2 Throwing ExceptionsIf 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”);}©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.8.2 Throwing ExceptionsEven 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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Fig. 8.3Two possible control flows of the try-catch statement with multiple catch blocks and the finally block.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.8.3 Propagating ExceptionsWhen 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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.8.3 Propagating ExceptionsAn 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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Fig. 8.4Figure 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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Fig. 8.4©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.8.3 Propagating ExceptionsIf 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 {...}©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.8.3 Propagating ExceptionsWithout 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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.8.3 Propagating ExceptionsDo 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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.8.3 Propagating ExceptionsThe following class, AgeInputVer4, allows client programmers to specify the lower and upper bounds of acceptable input values./*Chapter 8 Sample Class: Class to input ageFile: AgeInputVer4.java*/import javax.swing.*;class AgeInputVer4 { /** Default prompt message */ private static final String DEFAULT_MESSAGE = "Your age:"; ©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); } ©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.**@param low the lower bound of acceptable input values* @param 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); }} ©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** @param prompt message to prompt the user*/public int getAge(String prompt)throws Exception { String inputStr; int age; ©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"); } }} ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.8.3 Propagating Exceptions/*** Sets the lower and upper bounds of the input** @param low the lower bound of acceptable input values* @param high the upper bound of acceptable input values*/ private void setBounds(int low, int high) { lowerBound = low; upperBound = high; }}©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.8.4 Types of ExceptionsAll 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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Fig. 8.5Some classes in the inheritance hierarchy from the Throwable class. There are over 60 classes in the hierarchy.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.8.4 Types of ExceptionsThere 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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.8.4 Types of ExceptionsIf 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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.8.4 Types of ExceptionsIf a method is a propagator of runtime exceptions or errors, the throws clause is optional.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Fig. 8.6Callers 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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.Fig. 8.7It 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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.8.5 Programmer-Defined ExceptionsInstead 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. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.8.6 AssertionsThe 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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.8.6 AssertionsThe syntax for the assert statement isassert ;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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.8.6 AssertionsFor 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);}©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.8.6 AssertionsThe 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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.8.6 AssertionsFor example:public double fromDollar(double dollar){ assert exchangeRate > 0.0: “Exchange rate = “ + exchangeRate + “.\nIt must be a positive value.”;return (dollar * exchangeRate);}©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.8.6 AssertionsBefore 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 usingjavac –source 1.4 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.8.6 AssertionsTo run the program with assertions enabled, usejava –ea If the –ea option is not provided, the program is executed without checking assertions.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.8.6 AssertionsDo 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.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.8.6 AssertionsPrecondition 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. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.8.7 Supervisor-Subordinate Design PatternIn 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. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.8.7 Supervisor-Subordinate Design PatternIn the supervisor-subordinate design pattern, the supervisor object controls a subordinate object, but the subordinate can also call the supervisor’s method.©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.8.7 Supervisor-Subordinate Design PatternTo implement this design pattern, we must establish mutual references between the supervisor and subordinate. ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.8.7 Supervisor-Subordinate Design PatternFor example:class Supervisor { private Subordinate worker; public Supervisor ( ) { ... worker = new Subordinate(this); ... } ...}class Subordinate { private Supervisor boss; public Subordinate(Supervisor boss) { ... this.boss = boss; ... } ...}©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.8.7 Supervisor-Subordinate Design PatternWhen a new supervisor object is created, the subordinate is created also, and the mutual references are established as follows:©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
Các file đính kèm theo tài liệu này:
- chapter_8_032.ppt