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

Slides:



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

Exceptions Ensuring program reliability. Program correctness The term program correctness refers to a program’s working as advertised; that is, it produces.
Exceptions Don’t Frustrate Your User – Handle Errors KR – CS 1401 Spring 2005 Picture – sysprog.net.
Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.
Exception Handling and Format output
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 13 Exception Handling.
Exception Handling Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
SE-1020 Dr. Mark L. Hornick 1 More Exception Handling and Throwing Exceptions.
بسم الله الرحمن الرحيم CPCS203: Programming II. Objectives After you have read and studied this chapter, you should be able to –Improve the reliability.
SE-1020 Dr. Mark L. Hornick 1 Exceptions and Exception Handling.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Chapter Chapter 8 Exceptions and Assertions.
EXCEPTIONS. What’s an exception?? Change the flow of control when something important happens ideally - we catch errors at compile time doesn’t happen.
Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Exception Handling Topics We will discuss the following main topics: – Handling Exceptions – Throwing Exceptions – More about Input/Output Streams.
Exception handling Dealing with life’s little surprises.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exceptions Handling.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 17 Exceptions and.
Exceptions Three categories of errors: Syntax errors Runtime errors Logic errors Syntax errors: rules of the language have not been followed. Runtime error:
Chapter 8 Exceptions. Topics Errors and Exceptions try-catch throwing Exceptions Exception propagation Assertions.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Exceptions. Errors and Exceptions An error is a bug in your program –dividing by zero –going outside the bounds of an array –trying to use a null reference.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exceptions and Assertions Animated Version.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. COMPSCI 125 Spring 2005 Chapter 8  Errors and Exceptions Throwable class.
1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
Exceptions and Assertions Recitation – 03/13/2009 CS 180 Department of Computer Science, Purdue University.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
Introduction to Java Chapter 11 Error Handling. Motivations When a program runs into a runtime error, the program terminates abnormally. How can you handle.
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Exception Handling in Java Course Lecture Slides 7 th July 2010 “ Admitting.
Java Software Solutions Foundations of Program Design Sixth Edition
Preventing and Correcting Errors
Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions.
Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
Object Oriented Programming
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
Java Programming: Guided Learning with Early Objects
Java I/O Java I/O is based on input streams and output streams. All input and output are defined in the Java IO package. 1.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
1 Exception handling in Java Reading for this lecture: Weiss, Section 2.5 (exception handling), p. 47. ProgramLive, chapter 10. I need to know whether.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
Exceptions and Assertions Chapter 15 – CSCI 1302.
Exceptions Handling Prepared by: Ligemm Mae del Castillo.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
1 Chapter 15 Exceptions and Assertions. 2 Objectives F To know what is exception and what is exception handling (§15.2). F To distinguish exception types:
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
DCS 2133 Object Oriented Programming ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Exception Handling.
Lecture 5: Exception Handling and Text File I/O Michael Hsu CSULA.
Exception Handling. You learned that there are three categories of errors: syntax errors, runtime errors, and logic errors. Syntax errors arise because.
Exceptions in the Java programming language J. W. Rider.
Chapter 10 – Exception Handling
CS1101: Programming Methodology Recitation 7 – Exceptions
Exception Handling and Format output-CS1050-By Gayani Gupta
Chapter 6-3 (Book Chapter 8)
Handling Exceptions.
Chapter 15 – Exception Handling
Chapter 12 Exception Handling
Chapter 6-3 (Book Chapter 8)
Exception Handling Contents
Presentation transcript:

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

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

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

©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

©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

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

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

©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

©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

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

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

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

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

©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

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

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

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

©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

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

©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

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

©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

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

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

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

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

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

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

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

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

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

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

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

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

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

©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

©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

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

©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

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

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

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

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

©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; }

©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

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