Exceptions and Assertions Recitation – 03/13/2009 CS 180 Department of Computer Science, Purdue University.

Slides:



Advertisements
Similar presentations
Chapter 17 Failures and exceptions. This chapter discusses n Failure. n The meaning of system failure. n Causes of failure. n Handling failure. n Exception.
Advertisements

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 8 Exceptions and Assertions.
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
Exceptions Ensuring program reliability. Program correctness The term program correctness refers to a program’s working as advertised; that is, it produces.
CSM-Java Programming-I Spring,2005 Exceptions Lesson - 7.
Exceptions Don’t Frustrate Your User – Handle Errors KR – CS 1401 Spring 2005 Picture – sysprog.net.
Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.
Exception Handling and Format output
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 13 Exception Handling.
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.
Java Exceptions. Exceptions Often in computing, operations cannot properly execute because some sort of error has occurred. Some examples: Often in computing,
Exception Handling1. 2 Exceptions  Definition  Exception types  Exception Hierarchy  Catching exceptions  Throwing exceptions  Defining exceptions.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology/ George Koutsogiannakis 1.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Exceptions Chapter 18 Programs: DriverException2 DriverException TestAgeInputException.
Chapter Chapter 8 Exceptions and Assertions.
1 / 89 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 11 Programming Fundamentals using Java 1.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
Exception handling Dealing with life’s little surprises.
EXCEPTIONS Def: An exception is a run-time error. Examples include: attempting to divide by zero, or manipulate invalid data.
©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:
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.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Exceptions CIS 304 Intermediate Java Programming for Business.
©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.
CS November 2009 Exceptions in Java. Prof. Gries is lecturing in India for the next 7 days or so. Today’s reading: Ch. 10. Next lecture’s reading:
1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
Exception Handling Recitation – 10/(23,24)/2008 CS 180 Department of Computer Science, Purdue University.
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.
Example 1 :- Handling integer values public class Program1 { public static void main(String [] args) { int value1, value2, sum; value1 = Integer.parseInt(args[0]);
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.
06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.
Java Programming Exception Handling. The exception handling is one of the powerful mechanism provided in java. It provides the mechanism to handle the.
Handling Exceptions in java. Exception handling blocks try { body-code } catch (exception-classname variable-name) { handler-code }
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.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 15 Exceptions and.
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.
BIO Java 1 Exception Handling Aborting program not always a good idea – can’t lose messages – E-commerce: must ensure correct handling of private.
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.
1 Advanced Flow of Control : Introduction This chapter focuses on: –exception processing –catching and handling exceptions –creating new exceptions –exception.
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.
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 There's an exception to every rule.. 2 Introduction: Methods  The signature of a method includes  access control modifier  return type 
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:
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
CSE 1020: Exceptions and A multiclass application Mark Shtern 1-1.
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.
DCS 2133 Object Oriented Programming ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Exception Handling.
CS1101: Programming Methodology Recitation 7 – Exceptions
Chapter 15 – Exception Handling
E x c e p t i o n s Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. — Martin Golding.
Exception Handling.
E x c e p t i o n s Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. — Martin Golding.
Exceptions References: Jacquie Barker, Beginning Java Objects; Rick Mercer, Computing Fundamentals With Java; Wirfs-Brock et. al., Martin Fowler, OOPSLA.
Java Basics Exception Handling.
Presentation transcript:

Exceptions and Assertions Recitation – 03/13/2009 CS 180 Department of Computer Science, Purdue University

Project 6 and Exam 2 Project 6 posted, three-week project (including the spring break week) Milestone due on March 25 th, 10 pm Final project due on April 1 st, 10pm Start early! Exam 2 date and the milestone due date are in the same week! Exam 2: Tuesday, March 24th, 6:30 PM to 7:30 PM in MTHW, 210 All questions on the class newsgroup. Evening consulting hours MTW 7-10 p.m. in LWSN B146.

Handling Exceptions Goal  Improve the code reliability and robustness Exception  An error condition that can occur during the normal course of program execution  try/catch– try executing the exception handling routine when the exception occurs (is thrown)  When an exception is thrown, we say it is caught when the corresponding exception handling routine is executed

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 Throwing Exceptions A thrown exception must be handled by either catching it or propagating it to other methods. public int getAge() { inputStr = JoptionPane.showInputDialog(null, PROMPT); int age; try { age = Integer.parseInt( inputStr ); return age; } catch( NumberFormatException nfe ) { JoptionPane.showMessageDialog( null, “Bad Number”); } }

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 5 Propagating Exceptions If a method can throw an exception but does not catch it (exception propagator), it must alert the programmer to the possibility of an exception by including a throws clause. Example: public void displayAge throws NumberFormatException {  int age = getAge();  JoptionPane.showMessageDialog( null, “Your age is ” + age); }

Multiple catch Blocks try { String s = null; int i = s.indexOf(“a”); } catch (NullPointerException e) { // 1st catch block System.out.println("you caught an NPE"); } catch (Exception e) { // 2nd catch block System.out.println("you caught an E"); } The exception gets caught by the 1 st catch block. The 2 nd catch block will not be executed. The catch blocks should go from specific to less specific. Why?

Finally… We have this (s is a string): try { int i = s.indexOf(“a”); return i; } catch (NullPointerException e) { // 1st catch block System.out.println("you caught an NPE"); } catch (Exception e) { // 2nd catch block System.out.println("you caught an E"); } finally { System.out.println(“done”); } What’s the result if s = null? s = “b”?

The Hierarchy Throwable Error Exception ArithmeticException NullPointerException IllegalArgumentException NumberFormatException RunTimeException IOException AssertionError

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 9 Types of Exceptions Checked Exception  Exception that is checked at compile time. Unchecked Exception  All others, also called runtime exceptions – detected only at runtime.  Examples: trying to divide a number by 0 (ArithmeticException) trying to convert a string with letters to an integer (NumberFormatException)

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 10 Types of Exceptions( Cont'd ) If a method throws a checked exception, the caller of that method must explicitly include the try/catch or the throws clause in the method header. If a method throws a runtime exception, the use of the try/catch statement or throws clause is optional. Is this wrong? public void check( int num ) { if( num < 0 ) { throw new IllegalArgumentException(); }

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 11 Programmer Defined Exceptions Simple example: class AgeInputException extends Exception { private static final String DEFAULT_MSG = “Input out of bounds”; public AgeInputException( String msg ) { super( msg ); //call the parent’s constructor } public AgeInputException(int low, int high) { super( DEFAULT_MSG ); }

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 12 Programmer Defined Exceptions When to use them?  When we want the client programmer to handle the thrown exceptions we defined explicitly to increase the code robustness Should a customized exception class be a checked or unchecked exception?  Hint: Refer to previous slides

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 13 Assertions Use assertions to detect internal errors. Use exceptions to notify the client programmer of the misuse of our class. When assertions fail, an AssertionError is thrown. public void withdraw( double amount) throws IllegalArgumentException { if( amount <= 0 ) { throw new IllegalArgumentException( “Amount must be positive” ); } double oldBalance = balance; balance -= amount; assert balance < oldBalance : “wrong balance!”; // this is a postcondition assertion }

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 14 Assertion Example What is wrong with the following? public void doWork( int num ) { assert num > 0; total += num; } Do not use assertions to check validity of an argument. Use them for internal programming errors, exceptions are for misuse of classes.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 15 Enjoy the Spring Break ~~ But first a short quiz :) Quiz:  Are unchecked exceptions same as runtime exceptions? What are the examples of those exceptions?