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

Slides:



Advertisements
Similar presentations
Exceptions Ensuring program reliability. Program correctness The term program correctness refers to a program’s working as advertised; that is, it produces.
Advertisements

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.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 15: Exception Handling.
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,
Chapter 16: Exception Handling C++ Programming: From Problem Analysis to Program Design, Fifth Edition.
Objectives In this chapter you will: Learn what an exception is Learn how to handle exceptions within a program See how a try / catch block is used to.
 Both System.out and System.err are streams—a sequence of bytes.  System.out (the standard output stream) displays output  System.err (the standard.
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.
 2005 Pearson Education, Inc. All rights reserved Exception Handling.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Exceptions Chapter 18 Programs: DriverException2 DriverException TestAgeInputException.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 16: Exception Handling.
Chapter Chapter 8 Exceptions and Assertions.
Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
E XCEPTION H ANDLING Chapter 11 C S 442: A DVANCED J AVA P ROGRAMMING.
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.
Exceptions Used to signal errors or unexpected situations to calling code Should not be used for problems that can be dealt with reasonably within local.
Chapter 8 Exceptions. Topics Errors and Exceptions try-catch throwing Exceptions Exception propagation Assertions.
©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.
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.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 17 Exceptions and.
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.
Java Software Solutions Foundations of Program Design Sixth Edition
1 Exception Handling Introduction to Exception Handling Exception Handling in PLs –Ada –C++ –Java Sebesta Chapter 14.
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.
Chapter 12: Exception Handling
Handling Exceptions in java. Exception handling blocks try { body-code } catch (exception-classname variable-name) { handler-code }
Java Programming: Guided Learning with Early Objects
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 15 Exceptions and.
Introduction to Exception Handling and Defensive Programming.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Chapter 14: Exception Handling. Objectives In this chapter, you will: – Learn what an exception is – Learn how to handle exceptions within a program –
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.
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.
CS1101X: Programming Methodology Recitation 5 Exceptions & Characters and Strings.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 24.1 Test-Driving the Enhanced Car Payment.
Exceptions and Assertions Chapter 15 – CSCI 1302.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Chapter 15: Exception Handling C++ Programming: Program Design Including Data Structures, Fifth Edition.
EXCEPTIONS There's an exception to every rule.. 2 Introduction: Methods  The signature of a method includes  access control modifier  return type 
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:
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
(c) University of Washington10-1 CSC 143 Java Errors and Exceptions Reading: Ch. 15.
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.
Exceptions in the Java programming language J. W. Rider.
Introduction to OOP with Java 4th Ed, C. Thomas Wu
Chapter 10 – Exception Handling
CS1101: Programming Methodology Recitation 7 – Exceptions
Exception Handling and Format output-CS1050-By Gayani Gupta
Chapter 14: Exception Handling
Chapter 6-3 (Book Chapter 8)
Exception Handling Chapter 9.
Exception Handling Chapter 9 Edited by JJ.
Chapter 6-3 (Book Chapter 8)
CS-1020 and Exception Handling
Presentation transcript:

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

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

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

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

©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

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

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

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

©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

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

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

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

©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:";

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

©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

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

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

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

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

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

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

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

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