©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 8 - 1 Chapter 8 Exceptions and Assertions Animated Version.

Slides:



Advertisements
Similar presentations
Topics Introduction Types of Errors Exceptions Exception Handling
Advertisements

CMSC 202 Exceptions 2 nd Lecture. Aug 7, Methods may fail for multiple reasons public class BankAccount { private int balance = 0, minDeposit =
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 8 Exceptions and Assertions.
Exceptions Ensuring program reliability. Program correctness The term program correctness refers to a program’s working as advertised; that is, it produces.
CS102--Object Oriented Programming
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.
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.
Slides prepared by Rose Williams, Binghamton University Chapter 9 Exception Handling.
©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.
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. Chapter Chapter 13 Inheritance and Polymorphism Animated Version.
06 - Exceptions. 2 ©S. Uchitel, 2004 A familiar sight? Bluescreen.scr.
©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.
Fall 2007CS 225 Program Correctness and Efficiency Chapter 2.
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
Preventing and Correcting Errors
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.
Java Programming Exceptions Handling. Topics: Learn about exceptions Try code and catch Exceptions Use the Exception getMessage() method Throw and catch.
Chapter 12: Exception Handling
Java Programming: Guided Learning with Early Objects
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.
Data Structures Using Java1 Chapter 2 Inheritance and Exception Handling.
Chapter 12 Handling Exceptions and Events. Chapter Objectives Learn what an exception is Become aware of the hierarchy of exception classes Learn about.
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.
Chapter 15: Exception Handling C++ Programming: Program Design Including Data Structures, Fifth Edition.
Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
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.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 13 Inheritance and Polymorphism.
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)
EE422C Software Implementation II
Chapter 6-3 (Book Chapter 8)
Presentation transcript:

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exceptions and Assertions Animated Version

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 mechanisms. –Write methods that propagate exceptions. –Implement the try-catch blocks for catching and handling exceptions. –Write programmer-defined exception classes. –Distinguish the checked and unchecked, or runtime, exceptions.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Definition 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.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Not Catching Exceptions String inputStr; int age; inputStr = JOptionPane.showInputDialog(null, "Age:"); age = Integer.parseInt(inputStr); java.lang.NumberFormatException: ten at java.lang.Integer.parseInt(Integer.java:405) at java.lang.Integer.parseInt(Integer.java:454) at Ch8Sample1.main(Ch8Sample1.java:20) Error message for invalid input

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Catching an Exception inputStr = JOptionPane.showInputDialog(null, "Age:"); try { age = Integer.parseInt(inputStr); } catch (NumberFormatException e){ JOptionPane.showMessageDialog(null, "’" + inputStr + "‘ is invalid\n" + "Please enter digits only"); } trycatch

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Remaining statements in the try block is skipped. try {... } catch (Exception e) {... } try-catch Control Flow Assume throws an exception. Assume throws an exception. Exception Statements in the catch block are executed. And the execution continues to the next statement try {... } catch (Exception e) {... } No Exception Statements in the catch block are skipped. All statements in the try block are executed.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Getting Information There are two methods we can call to get information about the thrown exception: –getMessage –printStackTrace try {... } catch (NumberFormatException e){ System.out.println(e.getMessage()); System.out.println(e.printStackTrace()); }

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Multiple catch Blocks A single try-catch statement can include multiple catch blocks, one for each type of exception. try {... age = Integer.parseInt(inputStr);... val = cal.get(id); //cal is a GregorianCalendar... } catch (NumberFormatException e){... } catch (ArrayIndexOutOfBoundsException e){... }

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter All catch blocks are skipped. try {... }... } No Exception Multiple catch Control Flow All statements in the try block are executed and throw no exceptions. Remaining statements in the try block is skipped. try {... }... } Assume throws an exception and is the matching block. Assume throws an exception and is the matching block. Exception Statements in the matching catch block are executed.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter The finally Block There are situations where we need to take certain actions regardless of whether an exception is thrown or not. We place statements that must be executed regardless of exceptions in the finally block.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter try-catch-finally Control Flow No Exception try { } } finally {... } Assume throws an exception and is the matching block. Assume throws an exception and is the matching block. Exception try { } } finally {... } finally block is executed.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Propagating Exceptions Instead of catching a thrown exception by using the try- catch statement, we can propagate the thrown exception back to the caller of our method. The method header includes the reserved word throws. public int getAge( ) throws NumberFormatException {... int age = Integer.parseInt(inputStr);... return age; }

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Throwing Exceptions We can write a method that throws an exception directly, i.e., this method is the origin of the exception. Use the throw reserved to create a new instance of the Exception or its subclasses. The method header includes the reserved word throws. public void doWork(int num) throws Exception {... if (num != val) throw new Exception("Invalid val");... }

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Exception Thrower 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.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Types of Exception Throwers 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.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Sample Call Sequence try { B(); } catch (Exception e){... } Method A try { C(); } catch (Exception e){... } Method B try { D(); } catch (Exception e){... Method C if (cond) { throw new Exception(); Method D propagator catcher AA B A B C A B C D Stack Trace

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Exception Types 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.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Throwable Hierarchy There are over 60 classes in the hierarchy.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Checked vs. Runtime 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.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Different Handling Rules 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. When calling a method that can throw runtime exceptions, it is optional to use the try-catch statement or modify the method header to include a throws clause.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Handling Checked Exceptions

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Handling Runtime Exceptions

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Programmer-Defined Exceptions Using the standard exception classes, we can use the getMessage method to retrieve the error message. By defining our own exception class, we can pack more useful information –for example, we may define a OutOfStock exception class and include information such as how many items to order AgeInputException is defined as a subclass of Exception and includes public methods to access three pieces of information it carries: lower and upper bounds of valid age input and the (invalid) value entered by the user.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 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.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Sample Use #1 public double deposit(double amount) { double oldBalance = balance; balance += amount; assert balance > oldBalance; } public double withdraw(double amount) { double oldBalance = balance; balance -= amount; assert balance < oldBalance; }

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Second Form 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 exception.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Sample Use #2 public double deposit(double amount) { double oldBalance = balance; balance += amount; assert balance > oldBalance : "Serious Error – balance did not " + " increase after deposit"; }

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Compiling Programs with Assertions Before Java 2 SDK 1.4, the word assert is a valid nonreserved identifier. In version 1.4 and after, 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

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Running Programs with 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.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Different Uses of 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 that is used to assert the control must flow to particular cases.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Problem Statement Implement a Keyless Entry System that asks for three pieces of information: resident’s name, room number, and a password. –A password is a sequence of characters ranging in length from 4 to 8 and is unique to an individual dorm resident. –If everything matches, then the system unlocks and opens the door. –We assume no two residents have the same name. –We use the provided support classes Door and Dorm. –Sample resident data named samplelist.dat can be used for development.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Overall Plan Tasks: –To begin our development effort, we must first find out the capabilities of the Dorm and Door classes. –Also, for us to implement the class correctly, we need the specification of the Resident class. In addition to the given helper classes and the Resident class, we need to design other classes for this application. –As the number of classes gets larger, we need to plan the classes carefully.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Design Document ClassPurpose Ch8EntranceMonitorThe top-level control object that manages other objects in the program. This is an instantiable main class. DoorThe given predefined class that simulates the opening of a door. DormThe given predefined class that maintains a list of Resident objects. ResidentThis class maintains information on individual dorm residents. Specification for this class is provided to us. InputHandlerThe user interface class for handling input routines. JOptionPaneThe standard class for displaying messages.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Class Relationships DoorJOptionPane Resident InputFrameCh8EntranceMonitor Dorm (main class)

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Development Steps We will develop this program in three steps: 1.Define the Resident class and explore the Dorm class. Start with a program skeleton to test the Resident class. 2.Define the user interface InputHandler class. Modify the top-level control class as necessary. 3.Finalize the code by making improvements and tying up loose ends.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Step 1 Design Explore the Dorm class Implement the Resident class, following the given specification Start with the skeleton main class

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Step 1 Code Directory: Chapter8/Step1 Source Files: Resident.java Ch8EntranceMonitor.java Directory: Chapter8/Step1 Source Files: Resident.java Ch8EntranceMonitor.java Program source file is too big to list here. From now on, we ask you to view the source files using your Java IDE.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Step 1 Test The purpose of Step 1 testing is to verify that the Dorm class is used correctly to open a file and get the contents of the file. To test it, we need a file that contains the resident information. A sample test file called testfile.dat is provided for testing purpose. –This file contains information on four residents. –This file was created by executing the SampleCreateResidentFile program, which you can modify to create other test data files.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Step 2 Design Design and implement the InputHandler class. Modify the main class to incorporate the new class.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Step 2 Code Directory: Chapter8/Step2 Source Files: Resident.java Ch8EntranceMonitor.java InputHandler.java Directory: Chapter8/Step2 Source Files: Resident.java Ch8EntranceMonitor.java InputHandler.java

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Step 2 Test The purpose of Step 2 testing is to verify the correct behavior of an InputHandler. We need to test both successful and unsuccessful cases. –We must verify that the door is in fact opened when the valid information is entered. –We must also verify that the error message is displayed when there’s an error in input. We should test invalid cases such as entering nonexistent name, corrent name but wrong password, not enetering all information, and so forth.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Step 3: Finalize Possible Extensions –Improve the user interface with a customized form window for entering three pieces of information. –Terminate the program when the administrator enters a special code