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.

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.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
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
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.
Exceptions and Exception Handling Carl Alphonce CSE116 March 9, 2007.
Exception Handling Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
Exceptions1 Syntax, semantics, and pragmatics. Exceptions2 Syntax, semantics, pragmatics Syntax –How it looks, i.e. how we have to program to satisfy.
© 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.
Exceptions and Exception Handling Carl Alphonce CSE116.
Exceptions1 Syntax, semantics, and pragmatics. Exceptions2 Syntax, semantics, pragmatics Syntax –How it looks, i.e. how we have to program to satisfy.
Exceptions Briana B. Morrison CSE 1302C Spring 2010.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
Exceptions and Exception Handling (2) Carl Alphonce CSE116.
Exceptions and Exception Handling (continued) Carl Alphonce CSE116.
Slides prepared by Rose Williams, Binghamton University Chapter 9 Exception Handling.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 17 Exceptions and.
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.
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.
Slides prepared by Rose Williams, Binghamton University Chapter 9 More Exception Handling.
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.
Java Software Solutions Foundations of Program Design Sixth Edition
What is an exception? An exception is: – an event that interrupts the normal processing of the program. –an error condition that violates the semantic.
Preventing and Correcting Errors
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 9 : Exception Handling King Fahd University of Petroleum & Minerals College of Computer.
Object Oriented Programming
Chapter 12: Exception Handling
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
Slides Credit Umair Javed LUMS Web Application Development.
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.
Exceptions1 Syntax, semantics, and pragmatics. Exception create If (some error){ throw new SomeException(”some message”); } Exceptions2.
Exceptions Handling the unexpected. RHS – SWC 2 The Real World So far, most of our code has been somewhat näive We have assumed that nothing goes wrong…
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.
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.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
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.
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.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
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.
Exception. Agenda Exception. Handling Exceptions. The finally Clause.
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
Introduction to Exceptions in Java CS201, SW Development Methods.
Lecture 5: Exception Handling and Text File I/O Michael Hsu CSULA.
Chapter 13 Exception Handling
Exception Handling Chapter 9.
Exception Handling and Reading / Writing Files
Exception Handling Chapter 9 Edited by JJ.
Exception Handling.
Effective Java, 3rd Edition Chapter 10: Exceptions
Web Design & Development Lecture 7
SWE 619 Last modified Fall 2007 Saket Kaushik, Paul Ammann
Effective Java, Chapter 9: Exceptions
Exception Handling.
Presentation transcript:

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 exception handler try { // statements that may throw an exception.. if (someCondition) throw new ExceptionName (); } catch (ExceptionName e) { // executed for ExceptionName } finally { // executed whether exception or not }

3 Java exception mech. (cont.) when searching for a catch block to handle an exception thrown, Java goes upward through the dynamic activation stack of method calls until it finds a matching catch block should use exceptions only for "exceptional" conditions, not for ordinary control flow may enable recovery from a failure can ensure release of critical resources at least, enables graceful shutdown

4 On exception handling a library shouldn't produce diagnostic output at an end user, or independently terminate a program instead, throw an exception and let a caller decide not every program needs to handle exceptions safely: –a simple application may produce a suitable diagnostic, let the system release all acquired resources, and let the user re-run the program with a more suitable input

5 Benefits of exception handling separates of error handling from normal processing provides a systematic way to report and handle exceptional situations (failures or errors) exceptions are necessary for making reusable libraries and components work: –the library component may detect an error, e.g., violation of a precondition, but cannot know how to handle it

6 Handling exceptions Generally, there are many ways to handle an exception: 1.let Java handle it (but don't supress it) 2.fix the problem that let to the exception and resume the program; but often, erroneous conditions are difficult or impossible to fix 3.log the problem and resume the program 4.log the problem and rethrow the exception 5.chain a low-level exception within a new higher-level exception (wrap inside as a parameter) and throw that 6.print/display/log out an error message and let the program terminate

7 Handling exceptions (cont.) no one-for-all solution, depends strongly on the specific requirements of the application it may well be OK to simply let the program terminate itself, and let the user try with better input

8 Java exception class hierarchy

9 Checked vs. unchecked exceptions checked exceptions are either caught by the method in which they occur, or you must declare that the method throws the exception checked exceptions force the programmer to deal with exceptional conditions; error situations become explicit and in principle the program becomes more reliable unchecked exceptions extend RuntimeException and, if uncaught, are handled by Java use checked exceptions for recoverable conditions and RuntimeExceptions for programming errors other object-oriented languages (C++, C#) don't have checked exceptions (but Clu did)

10 Guidelines avoid unnecessary use of exceptions exception handling is not meant to replace a simple test; for example: –reaching the end of a list should not throw a exception –the API offers a query method (hasNext) for that –but then going past the end should throw NoSuchElementException is a run-time exception that indicates a programming error don't wrap every statement in a separate try block –"throw early, catch late" at a higher-level system

11 Guidelines (cont.) don't suppress or ignore exceptions try {... some code that throws SomeException } catch (SomeException ex) { // OK: don't care } if a checked exception does not make sense to you, don't hesitate to convert it into an unchecked exception and throw it again } catch (SomeException ex) { throw new RuntimeException (ex) chaining constructors available since version 1.4

12 Guidelines (cont.) in some situations, the programmer may "know" that the code cannot throw any exceptions whatsoever of course, then it should be well documented and checked: try {... // actually cannot throw exceptions } catch (SomeException e) { assert false; // so shouldn't get here throw new RuntimeException (e); }

13 Guidelines (cont.) but don't catch unnecessarily high-level exceptions try {... some code that throws exceptions } catch (Exception ex) { } unchecked exceptions inherit RuntimeException class which inherits Exception the code above ignores all unchecked exceptions, as well

14 Guidelines (cont.) Favor the use of standard exceptions, for example: IllegalArgumentException: parameter value is inappropriate IllegalStateException: state is inappropriate for method call (before remove must call next) NullPointerException: null value where prohited IndexOutOfBoundsException: invalid index ConcurrentModificationException: modification of object has been detected where prohibited UnsupportedOperationException: object does not support method

15 Guidelines (cont.) document all exceptions thrown by each method using the tag for debugging, the string represention of an exception should contain the values of all objects that "contributed" to the exception higher layers can catch lower-level exceptions, and in their place, throw exceptions that are explainable in terms of the higher-level abstraction

16 Exception translation for example, a get () method may call more primitive operations with their own exceptions; the method can perform exception translation: public E get (int index) { ListIterator it = listIterator (index); try { return it.next (); } catch (NoSuchElementException e) { throw new IndexOutOfBoundsException ("Index: " + index); }

17 Exception chaining in exception chaining a lower-level exception is stored by the higher-level exception for debugging purposes: try { lowLevelOperation (); } catch (LowLevelException e) { throw new HighLevelException (e); // has chaining constructor } additionally, the class Throwable provides methods getCause () and initCause (Throwable cause) to get and set the original cause of the error situation

18 Failure atomicity ideally, attempt to achieve failure atomicity: –a failed method should leave the system in the state it was in prior to the call in principal, recovery is not possible if the system is left in an undetermined, possibly faulty state failure atomicity is expecially important for checked exceptions, from which the caller is expected to recover

19 Failure atomicity (cont.) public E pop () { // a bit trivial but illustrative if (size () == 0) throw new NoSuchElementException (); // now can safely modify the contents: E result = elements [--size]; elements [size] = null; // eliminate old reference return result; }

20 Using finally blocks finally clauses release resources no matter what a finally clause can be be used without a catch clause: Graphics g = image.getGraphics (); try { code that might throw exceptions } finally { g.dispose (); }

21 Using finally blocks (cont.) you can decouple try/catch and try/finally to make your code more readable: InputStream in =...; try { try { // ensure that stream is closed code that might throw exceptions } finally { in.close (); } } catch (IOException e) { // reports errors show error dialog } this resembles the use C++ destructors

22 Problems with finally blocks if a finally block itself throws an exception, the original exception becomes permanently lost as a rule, all clean-up code such as finally should be programmed not to throw any exceptions –very hard to enforce in practice, and –unfortunately, not all library methods necessarily respect the right spirit of exception handling

23 Problems finally blocks (cont.) if a try block or a catch clause contains a return statement, the finally block is (as always) executed before the return however, if the finally block itself contains a return, it then masks off the original return public static f (int n) { try {... return n * n; }... } finally { if (n == 2) return 0; // strange and unexpected }