Download presentation
Presentation is loading. Please wait.
1
Exceptions and Assertions Recitation – 03/13/2009 CS 180 Department of Computer Science, Purdue University
2
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.
3
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
4
©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”); } }
5
©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); }
6
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?
7
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”?
8
The Hierarchy Throwable Error Exception ArithmeticException NullPointerException IllegalArgumentException NumberFormatException RunTimeException IOException AssertionError
9
©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)
10
©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(); }
11
©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 ); }
12
©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
13
©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 }
14
©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.
15
©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?
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.