An Introduction to Programming and Object Oriented Design
An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 15 : Failures and Exceptions
Objectives ñ After studying this chapter you should understand the following: ñ The notion of program and method failure. ñ The Java exception mechanism: throwing and catching an exceptions, and exception propagation. ñ How to deal with method failure. ñ Also, you should be able to: ñ catch exceptions in try-catch blocks; ñ define and use exceptions based on problem constraints. May 2004 NH-Chapter 15 1
Failure ñ Inability of system to accomplish intended purpose. ñ A method can fail for two reasons: ñ Logical error in its implementation. ñ Inability to obtain needed resource from environment. ñ Programs containing error can do little about it at run -time, except offer helpful error message identifying and locating problem. May 2004 NH-Chapter 15 2
Failure ñ A system may need resources from ñ hardware, ñ operating system, ñ file system, ñ network, ñ data base, or ñ user to achieve its purpose. ñ System may be unable to provide needed resource. May 2004 NH-Chapter 15 3
Failure ñ exception: occurrence of a detectable, abnormal situation which may lead to system failure. ñ Can design programs so that program itself will detect some logical errors. May 2004 NH-Chapter 15 4
The Java exception mechanism ñ Allows for detecting, reporting, and handling exceptions. ñ Not to be used to handle normal, expected events. ñ Not just another control structure. ñ Java detects certain run-time errors, such as: ñ attempts to divide by zero ñ use of a null reference when an object is required. ñ System notifies program of error by throwing an exception from point at which error occurred. May 2004 NH-Chapter 15 5
The Java exception mechanism ñ A thrown exception involves transfer of control: ñ processor stops executing current sequence of statements, and ñ begins executing statements at a different point in program. ñ Exception is caught or handled at the point to which control is transferred. May 2004 NH-Chapter 15 6
The Java exception mechanism May 2004 NH-Chapter 15 7
The Java exception mechanism ñ An exception is modeled as an instance of Java class Throwable. ñ Error class and its subclasses represent conditions from which an ordinary program is not expected to recover. May 2004 NH-Chapter 15 8
The Java exception mechanism ñ A few standard exceptions which are subclasses of Runtime. Exception: ñArithmetic. Exception: an exceptional arithmetic situation has arisen, such as an integer division with zero divisor. ñClass. Cast. Exception: attempt made to cast reference to an inappropriate type. ñIllegal. Argument. Exception: method invoked with invalid or inappropriate argument, or inappropriate object. ñNull. Pointer. Exception: attempt to use a null reference in case where an object reference was required. ñSecurity. Exception: a security violation was detected. May 2004 NH-Chapter 15 9
The Java exception mechanism May 2004 NH-Chapter 15 10
Catching exceptions ñSyntactic code structure for the detection and handling of errors. try { statements : : } catch ( exception parameter 1 ) { statements : : } catch ( exception parameter 2 ) { statements : : Block where exceptions may be raised Blocks to catch exceptions } … May 2004 NH-Chapter 15 11
Catching exceptions ñExceptions are objects try { statements } catch ( Arithmetic. Exection e) { statements : : } catch ( Null. Pointer. Exception e ) { statements : : } catch ( Exception e ) { statements : : } May 2004 NH-Chapter 15 12
Catching exceptions ñ Processor first performs statements of the try block. ñ If no exceptions occur, try-catch is complete, and catch ignores clauses. ñ If an exception is thrown during execution of try block, an attempt is made to match exception to catch clause parameters. May 2004 NH-Chapter 15 13
Catching exceptions try { i = i/i; j = 0; name = s. name(); j = 1; } catch (Arithmetic. Exception e) { j = 3; } catch (Null. Pointer. Exception e) { j = 4; } catch (Exception e) { if (e instanceof Illegal. Argument. Exception) j = 6; else j = 5; } System. out. println(“The value of j is” + j); May 2004 NH-Chapter 15 14
Not caught exceptions : Propagated exceptions ñ A not caught exception: ñ Exception is thrown by execution of statement not part of a try-catch, or ñ Thrown exception does not match any catch clauses. ñ A not caught exception is propagated up the “call chain”. ñ If no method in call chain catches exception, program terminates with error message. May 2004 NH-Chapter 15 15
Call-chain and not caught exceptions May 2004 NH-Chapter 15 16
Checked and unchecked exceptions ñ The class Runtime. Exception and its subclasses are referred to as unchecked exception classes. ñ Other exception classes are checked exception classes. ñ A method’s specification must include a throws clause if is possible for a checked exception to be thrown in method, and method does not catch exception. May 2004 NH-Chapter 15 17
Checked and unchecked exceptions ñ The specification public String readline() throws IOException ñ Means that IOException is a checked exception. Method readline of java. io. Buffered. Reader can throw it. ñ If read. Line throws IOException, it is propagated to its caller, who must also include it in method specification if not caught, as it will be propagated to its own callers: public void skip () throws IOException { String s; IOException not s = input. read. Line(); caught! } May 2004 NH-Chapter 15 18
Using exceptions ñ Server promises to fulfill a contract only if client satisfies preconditions. public int index. Of (Object item) The index of the first occurrence of the specified item on this List, or -1 if this List does not contain the specified item. ñ If we remove specification of returning a -1 if item not found in list, need to have precondition that item is in list. ñ This puts an unreasonable burden on client. May 2004 NH-Chapter 15 19
Contract failures ñ A method fails if it is unable to complete a contract even though its client has satisfied all preconditions. ñ Three failure cases: ñ A logical error in the method. ñ The method is not able to obtain necessary resources. ñ The method invokes another method which fails. May 2004 NH-Chapter 15 20
Dealing with exceptions ñ Two ways of dealing with failure of logical structures. ñ Clean up and report the failure to caller (by throwing an exception). ñ Attempt to correct situation that caused exception, and try again. May 2004 NH-Chapter 15 21
File. Reader example ñjava. io. File. Reader constructor is specified as follows: public File. Reader (String file. Name) throws File. Not. Found. Exception, Security. Exception; ñ Since File. Reader may fail, and if client does not catch the exception thrown by File. Reader constructor, it will be propagated to its caller. ñ Thus get. Some. Data needs the following specification public void get. Some. Data () throws File. Not. Found. Exception, Security. Exception { File. Reader in; in = new File. Reader("Data. File"); … } May 2004 NH-Chapter 15 22
File. Reader example ñ get. Some. Data handles exceptions of File. Reader, and re-throw them to its clients. public void get. Some. Data () throws File. Not. Found. Exception, Security. Exception{ File. Reader in; try { in = new File. Reader (“Data. File”); … } catch (File. Not. Found. Exception e) { //cleanup throw e; // throws it again to its caller } } catch (Security. Exception e) { //cleanup throw e; // throws it again to its caller } May 2004 NH-Chapter 15 23
Cleanup ñ A method cannot know how its caller will respond to the exception. ñ Caller might be able to recover. ñ Important that method leave object in a consistent state (with all class invariants satisfied). ñ Method should make sure that object is consistent before reporting failure to caller. May 2004 NH-Chapter 15 24
File. Reader example (cont. ) ñ Suppose file is locked, but expect lock to be removed shortly. public void get. Some. Data () throws File. Not. Found. Exception, Security. Exception{ File. Reader in; boolean success = false; //Data file opened int try. Number = 0; //# of attempts to open datafile int delay = 5 * 1000; //wait in milli secs while (!success) try { try. Number = try. Number + 1; in = new File. Reader(“Data. File”); success = true; … } catch (Security. Exception e) { if (try. Number == 1) this. Thread. sleep(delay); else throw e; } } May 2004 NH-Chapter 15 25
Application defined exceptions ñ Useful to define own exception classes to pass certain information to client. ñ Example: throw exception if fail to get data. public class No. Data. Exception extends Exception { public No. Data. Exception () { super(); } public No. Data. Exception (String s) { super(s); } } May 2004 NH-Chapter 15 26
Application defined exceptions public void get. Some. Data () throws No. Data. Exception { try { in = new File. Reader(“Data. File”); … } catch (File. Not. Found. Exception e) { //cleanup throw new No. Data. Exception (“File does not exist”) } catch (Security. Exception e) { //cleanup throw new No. Data. Exception (“File cannot be accessed”); } } May 2004 NH-Chapter 15 27
Application defined exceptions ñ Exception class can pass state information from method detecting exception to method that handles it. public class Bad. Data. Exception extends Exception { public Bad. Data. Exception (int line. Number) { super(); this. line. Number = line. Number; } public int line. Number() { return this. line. Number; } private int line. Number; } May 2004 NH-Chapter 15 28
Exceptions ñ Structured as immutable objects: their interface includes no state-changing commands. May 2004 NH-Chapter 15 29
Dealing with logical errors ñ Sometimes a logical error causes a method to produce reasonable but incorrect results. ñ We can check preconditions, postconditions, and invariants. ñ If a client invokes a method without preconditions being satisfied, it is an error. May 2004 NH-Chapter 15 30
Dealing with logical errors ñ Assert statement used to verify preconditions. ñ Two forms: assert boolean. Expression ; assert boolean. Expression : expression ; //Interchange list. get(i) and list. get(j) // require 0 <= i, j < list. size() … private <Element> void interchange ( List<Element> list, int i, int j) { assert 0 <= i && i < list. size(): "precondition: illegal i"; assert 0 <= j && j < list. size(): "precondition: illegal j"; … May 2004 NH-Chapter 15 31
Dealing with logical errors ñ We can use assert to check post-conditions, and invariants. ñ Postconditions and invariants often too complex to verify with simple conditions. ñ Postconditions ñ can be tricky to handle; ñ often they involve comparing an object’s state after method execution to the object’s state prior to execution. ñ Including such checks depends on where we are in the development process. May 2004 NH-Chapter 15 32
Summary ñ Addressed program failure. ñ A method can fail for two fundamental reasons: ñ a logical error in its implementation (a programming “bug”); or ñ its inability to obtain some needed resource from the environment. ñ Examined exception mechanism provided by Java to deal with failures. May 2004 NH-Chapter 15 33
Summary ñ An exception mechanism is provided by the language for detecting, reporting, and handling failure. ñ An exception is a detectable, abnormal situation which may lead to system failure, modeled by an instance of the Java class Exception. ñ An Exception instance carries information about the exception from the point at which the exception occurred (is thrown) to the point at which it is handled (is caught). May 2004 NH-Chapter 15 34
Summary ñ The language structure for handling exceptions is the try-catch statement. ñ Exceptions thrown in the statements that comprise the try block can be handled in one of the catch clauses. ñ An exception thrown in a method and not caught in the method is propagated to the method’s caller. ñ A method fails if it cannot satisfy its contract even though the client has satisfied the method’s preconditions. A method that fails must not simply return to its client. It must inform the client of the failure by throwing an exception. May 2004 NH-Chapter 15 35
Summary ñ A method fails if it cannot satisfy its contract even though the client has satisfied the method’s preconditions. ñ A method that fails must not simply return to its client. It must inform the client of the failure by throwing an exception. May 2004 NH-Chapter 15 36
Summary ñ When a client is notified of a server’s failure (by server’s throwing an exception), there are only two possible courses of action client can take. ñ attempt to correct the situation that caused the failure, and try again; or ñ report failure to its caller, by throwing or propagating an exception. ñ Most often, the second alternative is the only one practical. May 2004 NH-Chapter 15 37
Summary ñ An application can define its own exception classes, by extending the class Exception of one of its subclasses. ñ Program defined exceptions can be useful in providing more specific information about the cause of the failure. May 2004 NH-Chapter 15 38
Summary ñ Logical errors, by their very nature, can be difficult to detect. ñ Can be useful, particularly during program development, to verify explicitly conditions such as preconditions that must hold in a correct program. May 2004 NH-Chapter 15 39
- Slides: 40