Effective Java, Chapter 9: Exceptions Items 57-65 Last modified Fall 2012 Paul Ammann.

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

Exceptions CSE301 University of Sunderland Harry Erwin, PhD.
Lilian Blot VARIABLE SCOPE EXCEPTIONS FINAL WORD Final Lecture Spring 2014 TPOP 1.
Exceptions Ensuring program reliability. Program correctness The term program correctness refers to a program’s working as advertised; that is, it produces.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 13 Exception Handling.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Fall 2013 Chapter 13 Exception.
Exceptions and Exception Handling Carl Alphonce CSE116 March 9, 2007.
Exceptions1 Syntax, semantics, and pragmatics. Exceptions2 Syntax, semantics, pragmatics Syntax –How it looks, i.e. how we have to program to satisfy.
Java Programming Exceptions. Java has a built in mechanism for error handling and trapping errors Usually this means dealing with abnormal events or code.
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.
Exceptions1 Syntax, semantics, and pragmatics. Exceptions2 Syntax, semantics, pragmatics Syntax –How it looks, i.e. how we have to program to satisfy.
CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 1 CPSC150 Exceptions When things.
Exceptions and Exception Handling (2) Carl Alphonce CSE116.
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.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 Exception Handling (in a nutshell). 2 Motivations When a program runs into a runtime error, the program terminates abnormally. How can you handle the.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. COMPSCI 125 Spring 2005 Chapter 8  Errors and Exceptions Throwable class.
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.
CS203 Java Object Oriented Programming Errors and Exception Handling.
Preventing and Correcting Errors
1 Exception Handling Introduction to Exception Handling Exception Handling in PLs –Ada –C++ –Java Sebesta Chapter 14.
June 14, 2001Exception Handling in Java1 Richard S. Huntrods June 14, 2001 University of Calgary.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
1 Exceptions and error handling. 2 Java exception mechanism when an error or exceptional condition occurs, you throw an exception which is caught by an.
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.
Exceptions1 Syntax, semantics, and pragmatics. Exception create If (some error){ throw new SomeException(”some message”); } Exceptions2.
07 Coding Conventions. 2 Demonstrate Developing Local Variables Describe Separating Public and Private Members during Declaration Explore Using System.exit.
Effective Java: Generics Last Updated: Spring 2009.
Exceptions Syntax, semantics, and pragmatics Exceptions1.
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.
Best Practices. Contents Bad Practices Good Practices.
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.
Exception Handling Programmers must deal with errors and exceptional situations: User input errors Device errors Empty disk space, no memory Component.
Computer Science 209 Software Development Handing Errors and Creating Documentation.
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
Exceptions and Assertions Chapter 15 – CSCI 1302.
CSE 332: C++ Statements C++ Statements In C++ statements are basic units of execution –Each ends with ; (can use expressions to compute values) –Statements.
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.
SWE 4743 Abstract Data Types Richard Gesick. SWE Abstract Data Types Object-oriented design is based on the theory of abstract data types Domain.
Programming & Debugging. Key Programming Issues Modularity Modifiability Ease of Use Fail-safe programming Style Debugging.
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:
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
Exception. Agenda Exception. Handling Exceptions. The finally Clause.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
Introduction to Exceptions in Java CS201, SW Development Methods.
Lecture 5: Exception Handling and Text File I/O Michael Hsu CSULA.
OOP Tirgul 7. What We’ll Be Seeing Today  Packages  Exceptions  Ex4 2.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Eighth Lecture Exception Handling in Java
Chapter 13 Exception Handling
Chapter 13 Exception Handling
Software Development Handing Errors and Creating Documentation
Syntax, semantics, and pragmatics
Chapter 12 Exception Handling and Text IO
SWE 332 Last Modified Spring 2010 Paul Ammann
Chapter 12 Exception Handling
CSC 143 Error Handling Kinds of errors: invalid input vs programming bugs How to handle: Bugs: use assert to trap during testing Bad data: should never.
Effective Java, 3rd Edition Chapter 10: Exceptions
CSE 143 Java Exceptions 1/18/2019.
Chapter 12 Exception Handling and Text IO Part 1
SWE 619 Last modified Fall 2007 Saket Kaushik, Paul Ammann
Effective Java, Chapter 9: Exceptions
Computer Science 340 Software Design & Testing
Exception Handling and Event Handling
Presentation transcript:

Effective Java, Chapter 9: Exceptions Items Last modified Fall 2012 Paul Ammann

Item 57: Use Exceptions only for Exceptional Conditions Don’t do this! try{ int i=0; while (true) { range[i++].climb(); } }catch(IndexOutOfBoundsException e){} Note that code may hide unrelated exception! Implications for API design A well designed API must not force its clients to use exception handling for ordinary flow control Provide state testing method instead of forcing client to catch exception.

More Item 57 Do this instead for (Mountain m: range) { m.climb(); } Note: (implicit) “State Testing” method: i < range.length No possibility of unintentionally hiding IndexOutOfBoundsException from climb() Bottom line: Don’t use exceptions for ordinary flow control

More Item 57 How about? try{ Iterator i = collection.iterator(); while (true) { Foo foo = (Foo) i.next();... } }catch(NoSuchElementException e){} versus: for (Iterator i = collection.iterator(); i.hasNext();){ Foo foo = (Foo) i.next();... }

More Item 57 Two basic options State testing method Doesn’t work in concurrent environment State may change between state test and actual call May be undesirable if state testing method is as much computation as actual call Then, it’s better to have a distinguished return value Distinguished return value May not be an unused special value Example: “null” for Object return types Iterator next() method can legitimately return “null” Faulty use of distinguished return value model harder to detect

Item 58: Checked vs. Unchecked Unchecked exceptions indicate programming errors Precondition violations Recovery is impossible Checked exceptions indicate recoverable conditions Force the caller to handle the exception

More Item 58 Use unchecked exceptions if client has nothing to do OutOfMemoryException client knows better doesn’t need try-catch block; if-then block would suffice. Use checked exceptions if client has some reasonable action IOException  Calling code is correct, but exception can still be raised!

Item 59: Avoid Unnecessary Use of Checked Exceptions try{ obj.action(args) }catch(SomeCheckedException e){ throw new Error (“Assertion Error”); } // should never happen What is the point of making a client do this? Conditions for using checked exceptions: Exceptional condition cannot be prevented by proper use of the API Programmer can take some useful action

More Item 59 Standard Transformation: if (obj.actionPermitted(args)) { obj.action(args); } else { // Handle exceptional condition } Or even simply (where appropriate): obj.action(args); // Client allows call to fail

Item 60: Favor Use of Standard Exceptions IllegalArgumentException - Inappropriate parameter; several special cases NullPointerException (param null where prohibited) IndexOutOfBoundsException (index param out of range) ClassCastException

More Item 60 IllegalStateException Object state is inappropriate for method invocation Object may not be initialized before calling accessing its state Special subtype: ConcurrentModificationException Concurrent modification detected where not allowed UnsupportedOperationException Object does not support the method Substitution principal

More Item 60 Reasons to use standard exceptions: Using your API is easier Reading your programs is easier Performance advantage (relatively minor) No additional namespace to manage Note that standard Java exception list is more than the 6 mentioned in Bloch

Item 61: Throw Exceptions Appropriate to the Abstraction Propagated exceptions may make no sense Higher layers should translate lower level exceptions // Bad example: public int min (int[] a) { int minVal = a[0]; // Bad: Throws IndexOutOfBoundsException for (int val: a) {if (val < minVal) minVal = val;} return minVal; }

More Item 61: Exception Chaining Transformation: try { // Use low level abstraction to satisfy contract } catch (LowerLevelException cause) { throw new HigherLevelException (cause); } Achieves 2 very different goals Gives client exception at expected level of abstraction Also preserves low level detail for failure analysis

Item 62: Document All Exceptions Thrown by Each Method Checked Exceptions: Declare (required by compiler) And Document tag in JavaDoc) Unchecked Exceptions: Document tag in JavaDoc) Don’t shortcut with superclass exceptions Example: Don’t catch “Exception” instead of NullPointerException Ok to document common exceptions at class level Example: “All methods in class throw NullPointerException if a null object reference is passed in any parameter”

Item 63: Include Failure-Capture Information in Detail Messages Uncaught exceptions result in printing of stack trace, including “detail” messages These messages should contain values of all parameters that “contributed to the exception” In other words, include relevant state information Example: IndexOutOfBoundsException includes upper bound, lower bound, and offending index

Item 64: Strive for Failure Atomicity Failure atomicity: A failed method invocation should leave the object in the state that it was in prior to the invocation Ways to achieve this effect: Design immutable objects Check parameters for validity before performing the operation Order the computation – parts that fail come before modification Write recovery code – cause the object to roll back its state Perform the operation on a temporary copy of the object

More Item 64: public int addMax(List list, Integer x) throws … //pre: true //post: if x is not max w.r.t. list, throw IAE // else append x to list Don’t throw exception in between modifications to state variables Procedure should have an atomic effect throw exception in the beginning if you are not sure you can pull it off

More Item 64 public Object pop() throws … { //Requires: this != EmptyStack //Modifies: this //Effects: pops this and returns top Object result = elements[--size]; elements[size] = null; return result; } // Note: Client can corrupt state – oops!

More Item 64 public Object pop() throws … { //Requires: //Modifies: this //Effects: If this empty throw ISE // else pop this and returns top if (size == 0) { throw new ISE(…); Object result = elements[--size]; elements[size] = null; return result; } // Note atomic execution, normal or exception

Item 65: Don’t Ignore Exceptions Programmers should never leave a catch block empty Its easy to ignore exceptions, but don’t! try{... }catch(Exception e){ } // empty catch block wont raise complaints // from compiler! Don’t do this!

More Item 65 If its empty, its highly suspect The purpose of exception is to force programmers handle exceptional conditions At least have a comment which explains why its ok to ignore this exception