Class Design: Handling Errors Reading: 2 nd Ed: Chapter 15 3 rd Ed: Chapter 11 Exercises 2 nd Ed: P15.5, P15.6 (Hint: look at documentation for Scanner.

Slides:



Advertisements
Similar presentations
CMSC 202 Exceptions 2 nd Lecture. Aug 7, Methods may fail for multiple reasons public class BankAccount { private int balance = 0, minDeposit =
Advertisements

Exceptions & exception handling Use sparingly. Things you can do with exceptions: 1. Define a new exception class. 2. Create an exception instance. 3.
Exceptions Ensuring program reliability. Program correctness The term program correctness refers to a program’s working as advertised; that is, it produces.
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.
COMP 121 Week 5: Exceptions and Exception Handling.
© 2004 Pearson Addison-Wesley. All rights reserved10-1 Chapter 10 : Exceptions Intermediate Java Programming Summer 2007.
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.
© The McGraw-Hill Companies, 2006 Chapter 15. © The McGraw-Hill Companies, 2006 Exceptions an exception is an event that occurs during the life of a program.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Exceptions Chapter 18 Programs: DriverException2 DriverException TestAgeInputException.
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.
Java Exceptions. Types of exceptions  Checked exceptions: A checked exception is an exception that is typically a user error or a problem that cannot.
(c) University of Washington11-1 CSC 143 Java More on Exceptions Reading: Ch. 15.
Lecture 28 More on Exceptions COMP1681 / SE15 Introduction to Programming.
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.
16-Jun-15 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.
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.
Java Exceptions. Intro to Exceptions  What are exceptions? –Events that occur during the execution of a program that interrupt the normal flow of control.
©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.
Java Exceptions. Intro to Exceptions  What are exceptions? –Events that occur during the execution of a program that interrupt the normal flow of control.
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.
CS203 Java Object Oriented Programming Errors and Exception Handling.
Java Software Solutions Foundations of Program Design Sixth Edition
Preventing and Correcting Errors
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
Program Errors Syntax errors Logic errors
CIS 270—Application Development II Chapter 13—Exception Handling.
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
Exceptions 1. Your computer takes exception Exceptions are errors in the logic of a program (run-time errors). Examples: Exception in thread “main” java.io.FileNotFoundException:
Handling Exceptions in java. Exception handling blocks try { body-code } catch (exception-classname variable-name) { handler-code }
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
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.
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
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.
Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.
Exceptions and Assertions Chapter 15 – CSCI 1302.
Class Design I Class Contracts Readings: 2 nd Ed: Section 9.5, Advanced Topic nd Ed: Section 8.5, Advanced Topic 8.2 Some ideas come from: “Practical.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
Exceptions in Java. What is an exception? An exception is an error condition that changes the normal flow of control in a program Exceptions in Java separates.
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.
(c) University of Washington10-1 CSC 143 Java Errors and Exceptions Reading: Ch. 15.
Exceptions Lecture 11 COMP 401, Fall /25/2014.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Effective Java, Chapter 9: Exceptions Items Last modified Fall 2012 Paul Ammann.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Introduction to Exceptions in Java CS201, SW Development Methods.
Lecture 5: Exception Handling and Text File I/O Michael Hsu CSULA.
Chapter 10 – Exception Handling
Exceptions 10-Nov-18.
EE422C Software Implementation II
Abdulmotaleb El Saddik University of Ottawa
CMSC 202 Exceptions 2nd Lecture.
CMSC 202 Exceptions 2nd Lecture.
CMSC 202 Exceptions 2nd Lecture.
CSC 143 Java More on Exceptions.
Exceptions 10-May-19.
Exceptions References: Jacquie Barker, Beginning Java Objects; Rick Mercer, Computing Fundamentals With Java; Wirfs-Brock et. al., Martin Fowler, OOPSLA.
Presentation transcript:

Class Design: Handling Errors Reading: 2 nd Ed: Chapter 15 3 rd Ed: Chapter 11 Exercises 2 nd Ed: P15.5, P15.6 (Hint: look at documentation for Scanner class!) 3 rd Ed: P11.9, P11.11 You will be expected to: incorporate exception handling into the design of a method's contract trace code that makes use of exception handling write code to throw, catch or propagate an exception write code that uses a finally block write code to define a new exception class compare and contrast checked and unchecked exceptions understand the consequence of using checked vs. unchecked exceptions

Class Design - Exceptions 2 Exceptions – Why do we need them? Remember the Account class? We added the following precondition to the deposit method: amount >= 0 What if the client fails to check the precondition? The customers won't be happy to find out that sloppy programming has resulted in losing money because of a simple mistake! MAIN POINT … The method where a problem is detected, is often not the method which can resolve the problem

Class Design - Exceptions 3 Exceptions – Why we need them? If a precondition is violated, we can have the method: return a special value (e.g., true/false) to indicate whether or not the operation was successful problem: print an error message problem: terminate the program problem:

Class Design - Exceptions 4 Exceptions – Why we need them? Instead, we can have the method throw an exception if the amount is negative. Benefits: We can neatly separate regular code from error handling code We can force the client to acknowledge the problem. We allow the client to decide how to handle the problem.

Class Design - Exceptions 5 What's a Java Exception? An exception is an object with a specific interface, that can be thrown. All exception classes are subclasses of the class Throwable defined in the Java library. Here are some of the methods of this class: Throwable(); Throwable( String message ); String getMessage(); void printStackTrace(); Exceptions encapsulate information about the kind of problem that has occurred (the message) and the stack of method calls that led to the problem (the stack trace).

Class Design - Exceptions 6 What's an exception? There are two types of exception: checked and unchecked. Checked exceptions are handled specially by the Java compiler. This provides warnings and reminders about exceptions to programmers. Methods that might throw checked exceptions, must declare it in their signature Methods that call another method throwing a checked exception must either: Catch the exception Also declare it in their signature

Class Design - Exceptions 7 What's an exception? Unchecked exceptions are subclasses of Java’s RuntimeException or Error class, while all others are checked exceptions. Methods that might throw unchecked exceptions, do not need to declare it in their signature Methods that call another method throwing an unchecked exception can optionally: Catch the exception If a method does not catch an exception, than the exception propagates to the method’s caller, and so on…. Error represents abnormal conditions that a program would normally not be expected to handle.

Class Design - Exceptions 8 Java Exception Hierarchy Numerous exceptions and errors are defined in various java packages. i.e., FileNotFoundException in java.io IOException in java.io NullPointerException in java.lang etc. Programmers can define their own exceptions as subclasses of Exception or its subclasses. Object Throwable Exception Error RunTimeException checked exceptions unchecked IOException

Class Design - Exceptions 9 Defining an Exception Class Returning to our Account example, suppose we decide to throw an exception when the amount is negative. First we must decide which exception class to use. We could use the class Exception in the Java library but we can capture more information by defining our own exception class. Let's define a class named IllegalValueException to represent the type of exception that will be thrown when we attempt to pass a negative amount. This will be a checked exception (more about this later).

Class Design - Exceptions 10 Defining an exception class public class IllegalValueException extends Exception { public IllegalValueException() { } public IllegalValueException(String msg) { super(msg); }

Class Design - Exceptions 11 Checked versus Unchecked … Why? Checked exceptions usually represent problems which are expected to occur, so they must be handled e.g. incorrect password Unchecked exceptions represent bugs in a method SO … explicitly declaring an unchecked exception in a method signature does not make sense … WHY?

Class Design - Exceptions 12 Throwing an Exception /** * Deposit money into the account amount The amount to be deposited * true IF amount >= 0 * THEN getBalance() + amount * ELSE getBalance() IllegalValueException if amount is negative */ public void deposit(double amount) throws IllegalValueException { if (amount < 0) throw new IllegalValueException("Error: Neg. amount"); balance = balance + amount; }

Class Design - Exceptions 13 Catching Exceptions Recall that IllegalValueException is a checked exception. This has consequences for a client calling our deposit method. The client code must do one of the following: catch the exception propagate (i.e., pass on) the exception to its caller (i.e., the method that called it) The type of exception thrown must be a sub-type (or equal type) as the catch parameter type

Class Design - Exceptions 14 Try/Catch Block try { //Normal code to execute //Can include other nested try/catch blocks } catch(ExceptionType1 name) { //Code to execute if exception type 1 is thrown in normal code } catch(ExceptionType2 name) { //Code to execute when exception type 2 is thrown in normal code } … possibly more catch blocks

Class Design - Exceptions 15 Client Catching an Exception public static void main( String[] args ) { Account instructorAccount = new Account ( “instructor”, ); try { instructorAccount.deposit( 100 ); System.out.println( "Balance: " + instructorAccount.getBalance() ); } catch( IllegalValueException e ) { System.out.println( e.getMessage() ); } } What happens when deposit is called?

Class Design - Exceptions 16 What happens when this code executes? public static void main( String[] args ) { Account instructorAccount = new Account ( “instructor”, ); try { instructorAccount.deposit( -100 ); System.out.println( "Balance: " + instructorAccount.getBalance() ); } catch( IllegalValueException e ) { System.out.println( e.getMessage() ); } }

Class Design - Exceptions 17 Client Propagating an Exception public void depositToAccount( Account anAccount, double amount ) throws IllegalValueException { anAccount.deposit( amount ); System.out.println( "Balance: " + anAccount.getBalance() ); } The method that calls deposit must either: catch the exception propagate the exception to its caller If it propagates the exception then its caller must either catch or propagate the exception and so on…

Class Design - Exceptions 18 Tracing an example call Trace the following code: public static void main( String[] args ) { Account anAccount = new Account ( “test”, 200 ); try { depositToAccount( anAccount, ); } catch( IllegalValueException e ) { System.out.println( e.getMessage() ); } }

Class Design - Exceptions 19 Tracing an example call Trace the following code: public static void main( String[] args ) { Account anAccount = new Account ( “test”, 200 ); try { depositToAccount( anAccount, ); } catch( IllegalValueException e ) { System.out.println( e.getMessage() ); } }

Class Design - Exceptions 20 Exception Propagation If the exception is propagated as far as main() and main() doesn't catch the exception, the program is terminated. The error message associated with the exception is printed on the screen along with the stack trace. Allowing your program to terminate when an exception is thrown is not acceptable in real software (and could lead to disaster in real code!)

Class Design - Exceptions 21 Unchecked Exceptions If a method throws an unchecked exception, the rules are different: it is not necessary to declare that the method throws the exception there is no requirement on the calling method to handle the exception (i.e., doesn’t have to catch or explicitly declare the exception in its signature) Assertion failures throw unchecked exceptions A good design is to use a global “safety-net” handler in “main” To handle all unforeseen circumstances

Class Design - Exceptions 22 Example public class ExamMarker { //... /** * Calculates the given mark as a percentage of max mark mark the given mark max the maximum mark for the exam the mark as a percentage of max */ public int percentage(double mark, double max) throws IllegalMarkException, IllegalMaxException { if ( max == 0 ) throw new IllegalMaxException( "Max is 0" ); if( mark max ) throw new IllegalMarkException( "Incorrect Mark Submitted" ); return (int)( mark / max * 100 ); }

Class Design - Exceptions 23 public static void main(String[] args) { ExamMarker marker = new ExamMarker(); Scanner input = new Scanner( System.in ); double mark, max; int percent; System.out.println( "Enter a mark for this exam and the max mark: " ); // cont'd

Class Design - Exceptions 24 while( input.hasNext() ) { mark = input.nextDouble(); max = input.nextDouble(); try { percent = marker.percentage( mark, max); System.out.println( "The exam mark is: " + percent + "%" ); } catch( IllegalMaxException e ) { System.out.println( "Exam Marker Error: " + e.getMessage() ); } catch( IllegalMarkException e ) { System.out.println( "Exam Marker Error: " + e.getMessage() ); }

Class Design - Exceptions 25 public class ExamMarkerException extends Exception { public ExamMarkerException(){ } public ExamMarkerException( String msg ) { super(msg); }

Class Design - Exceptions 26 public class IllegalMarkException extends ExamMarkerException { public IllegalMarkException(){ } public IllegalMarkException( String msg ) { super( msg ); } public class IllegalMaxException extends ExamMarkerException { public IllegalMaxException(){} public IllegalMaxException( String msg ) { super( msg ); }

Class Design - Exceptions 27 Question What will be output if we enter the following data on the keyboard? Give an example of data that we could enter on the keyboard to cause an IllegalMaxException to be thrown.

Class Design - Exceptions 28 Question What if we replace the two catch blocks in main() with the following? catch( ExamMarkerException e ) { System.out.println( "Exam Marker Error: " + e.getMessage() ); } How will the output change?

Class Design - Exceptions 29 Comments Note that methods can throw more than one type of exception. If we call a method that throws more than one type of exception we can have more than one catch block to handle each type of exception. Catch blocks must be ordered from the most specific type of exception (the one lowest in the inheritance hierarchy) to the least specific (the one highest in the hierarchy).

Class Design - Exceptions 30 Designing Exceptions Need to distinguish boundary cases that can be handled by the method from exceptional cases which should throw exceptions Define individual exception for each type of error can group them into hierarchies – allows more flexibility in handling them Exceptions thrown by a method are shown in the method’s comment using tag. Too many exceptions may make the method difficult to use.

Class Design - Exceptions 31 Example: Class Account Re-designed We redesign deposit and withdraw to throw exceptions in the error cases /** * A simple bank account for which the balance can never be * less than zero * getBalance() >= 0 getId()is unique and set when account is created getName()is set when account is created the values of getId() and getName() never change */ public class Account { private int id; private static int nextAccountId = 0; private String name; private double balance;.....

Class Design - Exceptions 32 /** * Deposit money into the account amount The amount to be deposited * amount >= 0 getBalance() + amount The current balance of the account */ public double deposit(double amount) { assert amount >= 0; balance = balance + amount; return balance }

Class Design - Exceptions 33 /** * Deposit money into the account amount The amount to be deposited * true IF amount >= 0 * THEN getBalance() + amount * ELSE getBalance() The current balance of the account IllegalValueException if amount is negative */ public double deposit(double amount) throws IllegalValueException { if (amount < 0) throw new IllegalValueException("Error: Neg. amount"); balance = balance + amount; return balance } Should it have “assert”? YES NO Another Design for Deposit

Class Design - Exceptions 34 /** * Withdraw money from the account amount The amount to be withdrawn true IF (amount >= 0 >= 0 ) * THEN getBalance() - amount * ELSE getBalance() The current balance of the account IllegalValueException if amount<0 NotEnoughMoneyException if getBalance()-amount<0 */ public double withdraw(double amount) throws IllegalValueException, NotEnoughMoneyException { if (amount < 0) throw new IllegalValueException("Error: Neg. amount"); if (balance - amount < 0) throw new NotEnoughMoneyException("Error: no $$$"); balance = balance - amount; return balance; }

Class Design - Exceptions 35 /** * Returns the string representation of an account * true the account represented as a string */ public String toString() { return "[ id = " + id + ", name = " + name + ", balance = " + balance + "]"; }

Class Design - Exceptions 36 Account Exceptions public class IllegalValueException extends AccountException { public IllegalValueException() {} public IllegalValueException(String msg) { super(msg); } public class NotEnoughMoneyException extends AccountException { public NotEnoughMoneyException() {} public NotEnoughMoneyException(String msg) { super(msg); } NOTE: We could use Java’s IllegalArgumentException instead of defining a new exception for illegal value

Class Design - Exceptions 37 Exercise class Weather { String sunshine(String s) throws SunException, RainException { if (s != null) { if (s.equals("Strong sun")) { return "Better use sunblock!"; } throw new SunException( “It won’t last long."); } throw new RainException("No sun today."); } void fog(String x) { try { System.out.println(snow(x)); } catch (ColdException ce) { System.out.println( “You should expect“ + ce.getMessage); } String snow(String s) throws ColdException { if (s != null && s.equals("Really cold")) { throw new ColdException(“dry snow"); } try { return sunshine(s); } catch (RainException re){ return "Terrible! “ + re.getMessage(); } catch (SunException se) { return " Don't worry “ + se.getMessage(); } Assuming that the exceptions used here are appropriately defined, what would the following calls produce? new Weather().fog(“Showers”); new Weather().fog(“Really Cold”); new Weather().fog(“Strong Sun”); new Weather().fog(null);

Class Design - Exceptions 38 The finally clause A finally clause can follow the catch clauses of a try block (or even a try block with no catch clauses): try { // code that may throw checked exceptions } catch( SomeException e ) { … } finally { … } The finally clause is executed whether or not an exception is thrown, and (if thrown) whether or not it was caught. It is often used to ensure that resources are released.