Presentation is loading. Please wait.

Presentation is loading. Please wait.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Exceptions Chapter 18 Programs: DriverException2 DriverException TestAgeInputException.

Similar presentations


Presentation on theme: "©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Exceptions Chapter 18 Programs: DriverException2 DriverException TestAgeInputException."— Presentation transcript:

1 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Exceptions Chapter 18 Programs: DriverException2 DriverException TestAgeInputException (Driver) AgeInputVer4

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.

4 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. The Hierarchy of Exceptions Classes Some classes in the inheritance hierarchy from the Throwable class. There are over 60 classes in the hierarchy. fatal system errors checked exceptions unchecked exceptions

5 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Java’s Exception-Handling Model Based on three operations: Claiming an exception Throwing an exception Catching an exception

6 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Example of Try and Catch Blocks try{ code that may throw exceptions } // catch exception catch (Exception1 exception){ handler for Exception1 } catch (Exception1 exception){ handler for Exception1 corrective action } finally{ System.out.println(“DONE”); }

7 ©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.

8 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Catching Exceptions String inputStr = JOptionPane.showInputDialog(null, "Please enter your age"); int number = Integer.parseInt(inputStr); The user typed in abc 123. User will get an error message such as Exception in thread “main” java.lang.NumberFormatException: for input string “abc 123” at java.lang.NumberFormatException: java:48> at java.lang.Integer.parseInt(Integer.java:447> at java.lang.Integer.parseInt(Integer.java:497> at DriverException2.main(DriverException2.java:21> The system has caught an exception called NumberFormatException – the program tried to convert a String to a numerical value Run program: DriverException2 in the Exception Folder

9 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 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. This mechanism is called exception handling. Run program: DriverException in the Exception Folder Note: You will get the same error message that you got for DriverException2

10 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 8.1 Catching Exceptions Stopped here 10/12/09 Monay inputStr = JOptionPane.showInputDialog(null, prompt); try { // wrap the statements that may throw // an exception with the try-catch // control statement age = Integer.parseInt(inputStr); } catch (NumberFormatException e){ JOptionPane.showMessageDialog(null, “’” + inputStr +“ is invalid\n” +“Please enter digits only”); }

11 ©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.

12 ©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.

13 ©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.

14 ©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

15 ©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. We are only interested in Exception errors.

16 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 8.1 Catching Exceptions - Error The Error is similar to an exception except it describes internal system errors. Such errors rarely occur. Little you can do beyond notifying the user and trying to terminate the program gracefully. Examples of subclasses of Error class: LinkageError, Virtual-MachineError, and AWTError. Subclasses of LinkageError indicate that a class has some dependency on another class, but that the latter class has changed incompatibly after the compilation of the former class.

17 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 8.1 Catching Exceptions - Error contd. Subclasses of VirtualMachineError indicate that the Java Virtual Machine is broken or has run out of resources necessary to continue operating AWTError is caused by a fatal error in the GUI components,

18 ©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 shows the sequence of calls made from the main method of the main class to the method that throws the exception

19 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 8.1 Catching Exceptions- getMessage and printStackTrace try { age = Integer.parseInt(inputStr) return age; // input okay so return the value and // exit } //otherwise catch the error catch (NumberFormatException e) { System.out.println(e.getMessage() ); e.printStackTrace(); }

20 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 8.1 Catching Exceptions- getMessage and printStackTrace contd. Enter abc 123 instead of an integer getMessage: For Input string “abc 123” printStackTrace: java.lang.NumberFormatException: For input string “abc 123” at java.lang.NumberFormatException for input string at java.lang.Integer.parseInt(Integer.java:447> at java.lang.Integer.parseInt(Integer.java:497> at DriverException. main(Driver Exception. java:21> Run DriverException The result of the printStackTrace is the same as the one when the system handled the thrown exception See DriverException2

21 ©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.

22 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 8.2 Throwing Exceptions: the user entered -10 try { inputStr = JOptionPane.showInputDialog(null, ”Please enter your age); int age = Integer.parseInt(inputStr); if (age < 0){ throw new Exception(“Negative age is invalid”); } } // end try block catch (NumberFormatException e){ System.out.println(e.getMessage() ); e.printStackTrace (); } // end catch block //The thrown exception is caught by this catch block { catch(Exception e){ JOptionPane.showMessageDialog(null, “Error: ” + e.getNessage()); }// end catch block Run program DriverException3

23 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 8.2 Throwing Exceptions: the user entered -10 Run program DriverException3

24 ©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 (subclasses) first before the more general exception classes (superclass). When an exception is thrown, its matching catch block is executed and the other catch blocks are ignored.

25 ©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.

26 ©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.

27 ©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”); }

28 ©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.

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

30 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 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.

31 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 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.

32 ©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.

33 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig. 8.4 Direction of call (green arrow) Reversing of call sequence (red arrow)

34 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 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 {... }

35 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Propagating Exceptions -Another These statements all throw an IOException, therefore we add throws IOException to the method that we define. public static void main(String [] args) throws IOException { BufferedReader bufReader = new BufferedReader(fileReader);... = new FileOutputStream(outFile);... outStream.write(byteArray);... outStream.close(); }

36 ©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. Unchecked exception RunTimeException describes programming errors, such as bad casting, accessing an out-of-bounds array, and numeric errors. Subclasses are RuntimeException, Arithmetic Exception, NullPointerException, and IndexOutOfBoundsException IllegalArgumentException Run ShowRunTime.java

37 ©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. Run programs: TestAgeInputException.java (driver) AgeInputVer4

38 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 8.4 Types of Exceptions Summary 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.

39 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. IOException class - Summary The IOException class describes errors related to input/output operations, such as invalid input, reading past the end of a file, and opening a nonexistence file. Subclasses are IOException or InterruptedIOException, EOFException, and FileNotFoundException

40 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 8.4 Types of Exceptions - Summary 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.

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

42 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 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.

43 ©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.

44 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 8.5 Programmer-Defined Exceptions public void withdraw (double amount) throws NegativeAmountException, Insufficient FundException { if ( amount < 0) throw NegativeAmountException this, amount, “withdraw”); if (balance < amount) throw new InsufficientFundException(this, amount); balance = balance – amount; }

45 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 8.5 Programmer-Defined Exceptions // NegativeAmountException.java: Negative amount exception public class NegativeAmountException extends Exception { /** Account information to be passed to the handlers */ private Account account; private double amount; private String transactionType; /** Construct a negative amount exception */ public NegativeAmountException(Account account, double amount, String transactionType) { super("Negative amount"); this.account = account; this.amount = amount; this.transactionType = transactionType; } // end constructor }// end NegativeAmountException class

46 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 8.5 Programmer-Defined Exceptions // InsufficientFundException.java: An exception //class for describing insufficient fund exception public class InsufficientFundException extends Exception { /** Information to be passed to the handlers */ private Account account; private double amount; /** Construct an insufficient exception */ public InsufficientFundException(Account account, double amount) { super("Insufficient amount"); this.account = account; this.amount = amount; } /** Override the "toString" method */ public String toString() { return "Account balance is " + account.getBalance(); }


Download ppt "©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Exceptions Chapter 18 Programs: DriverException2 DriverException TestAgeInputException."

Similar presentations


Ads by Google