chapter 17 failures and exceptions. this chapter discusses n failure. n the meaning of system...

37
Chapter 17 Failures and exceptions

Upload: megan-cox

Post on 26-Mar-2015

242 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 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

Chapter 17Failures and exceptions

Page 2: 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

This chapter discusses

Failure. The meaning of system failure. Causes of failure. Handling failure. Exception mechanism. Using Exception class and its

subclasses. Generating exceptions.

Page 3: 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

Failure

Inability of a system, at run-time, to accomplish its intended purpose.

A method can fail for two reasons: A logical error in its implementation. Its inability to obtain some needed

resource from the environment. Programs containing an error can do

little about it at run-time, except offer a helpful error message that will assist in identifying and locating the problem.

Page 4: 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

Failure (cont.)

A system may need resources from the hardware, the operating system, the file system, the network, a data base, or a user to achieve its purpose.

The system may be unable to provide the needed resource.

Page 5: 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

Failure (cont.)

exception: The occurrence of a detectable, abnormal situation which may lead to system failure.

We can design programs so that the program itself will detect some logical errors.

Page 6: 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

The Java exception mechanism The exception mechanism includes the facilities

for detecting, reporting, and handling exceptions. The exception mechanism should not be used to

handle normal, expected events. It is not just another control structure. The Java run-time system or interpreter detects

certain run-time errors, such as attempts to divide by zero or to use a null reference when an object is required.

The system notifies the program of the error by throwing an exception from the point at which the error occurred.

Page 7: 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

The Java exception mechanism (cont.) A thrown exception involves a transfer of

control: the processor stops executing the current sequence of statements, and begins executing statements at a different point in the program.

The exception is caught or handled at the point to which control is transferred.

Page 8: 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

The Java exception mechanism (cont.)

Page 9: 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

The Java exception mechanism (cont.) An exception is modeled as an instance

of the Java class Throwable. The Error class and its subclasses

represent conditions from which an ordinary program is not expected to recover.

Page 10: 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

The Java exception mechanism (cont.) A few standard exceptions which are

subclasses of RuntimeException: ArithmeticException: an exceptional arithmetic

situation has arisen, such as an integer division with zero divisor.

ClassCastException: an attempt made to cast a reference to an inappropriate type.

IllegalArgumentException: a method was invoked with an invalid or inappropriate argument, or an inappropriate object.

NullPointerException: an attempt was made to use a null reference in a case where an object reference was required.

SecurityException: a security violation was detected.

Page 11: 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

The Java exception mechanism (cont.)

Page 12: 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

Catching exceptions

try {

statements1

} catch ( exception parameter1 ) {

statements2

} catch ( exception parameter2 ) {

statements3

} …

Page 13: 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

Catching exceptions (cont.)try {

statements1

} catch ( ArithmeticExection e) {

statements2

} catch ( NullPointerException e ) {

statements3

} catch ( Exception e ) {

statements4

}

Page 14: 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

Catching exceptions (cont.) The processor first performs the

statements of the try block. If no exceptions occur, the try-catch is

complete, and the catch clauses are ignored.

If an exception is thrown during execution of the try block, an attempt is made to match the exception to the catch clause parameters.

Page 15: 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

Catching exceptions (cont.)try {

i = i/i;j = 0;name = s.name();j = 1;

} catch (ArithmeticException e) {j = 3;

} catch (NullPointerException e) {j = 4;

} catch (Exception e) {if (e instanceof IllegalArgumentException) j = 6;else j = 5;

}System.out.println(“The value of j is” + j);

Page 16: 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

Propagated exceptions

If an exception is thrown by the execution of a statement that is not part of a try-catch, or if an exception is generated that does not match any of the catch clauses, the exception is propagated up the “call chain” to the calling method.

Page 17: 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

Checked and unchecked exceptions The class RuntimeException and its

subclasses are referred to as unchecked exception classes.

Other exception classes are checked exception classes.

A method’s specification must explicitly state if it is possible for the method to throw a checked exception to its caller.

Page 18: 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

Checked and unchecked exceptions (cont.)public String readline() throws IOException

(An IOException is propagated to readLine’s

caller)

public void skip () throws IOException {

String s;

s = input.readLine();

}

public void skip () throws EOFException, FileNotFoundException {

}(can propagate more than one kind of exception)

Page 19: 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

Using exceptions

The server promises to fulfill a contract only if the client satisfies the preconditions.

public int indexOf (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 removed the specification of returning a -1 if the item was not found in the list, we would need to have a precondition that the item be found in the list.

This puts an unreasonable burden on the client.

Page 20: 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

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.

Page 21: 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

Dealing with exceptions

There are only two ways of dealing with failure of logical structures. Clean up and report the failure to the

caller (by throwing an exception). Attempt to correct the situation that

caused the exception, and try again.

Page 22: 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

FileReader example

A class java.io.FileReader constructor is specified as follows.

public FileReader (String fileName) throws FileNotFoundException, SecurityException

SecurityException is an unchecked exception, but is something we wish to address.

public void getSomeData() throws FileNotFoundException,SecurityException{FileReader in;in = new FileReader (“DataFile”);…

}

Page 23: 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

FileReader example (cont.)public void getSomeData () throws

FileNotFoundException,SecurityException{

FileReader in;try { in = new FileReader (“DataFile”); …} catch (FileNotFoundException e) { //cleanup throw e;}} catch (SecurityException e) { //cleanup throw e;

}

Page 24: 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

Cleanup

A method cannot know how its caller will respond to the exception.

The caller might be able to recover. It is important that the method leave its

object in a consistent state (with all class invariants satisfied).

A method should make sure that the object is consistent before reporting failure to its caller.

Page 25: 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

FileReader example (cont.) Suppose a file is locked, but we expect the lock to be

removed shortly.public void getSomeData () throws

FileNotFoundException,SecurityException{FileReader in;boolean success = false;//Data file openedint tryNumber = 0;//# of attempts to open datafileint delay = 5 * 1000;//wait in millsecswhile (!success) try {

tryNumber = tryNumber + 1;in = new FileReader(“DataFile”);success = true;…

} catch (SecurityException e) {if (tryNumber == 1) thisThread.sleep(delay);else throw e;

}}

Page 26: 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

Application defined exceptions It is sometimes useful to define our own

exception classes to pass certain information to the client.

Example: throw an exception if we fail for any reason to get data.

public class NoDataException extends Exception {public NoDataException () { super();}public NoDataException (String s) { super(s);}

}

Page 27: 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

Application defined exceptions (cont.)public void getSomeData () throws

NoDataException {try { in = new FileReader(“DataFile”); …} catch (FileNotFoundException e) { //cleanup throw new NoDataException

(“File does not exist”)} catch (SecurityException e) { //cleanup throw new NoDataException

(“File cannot be accessed”);}

}

Page 28: 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

Application defined exceptions (cont.) An exception class also can pass state information

from the method detecting the exception to the method that will handle it.

public class BadDataException extends Exception {public BadDataException (int lineNumber) { super(); this.lineNumber = lineNumber;}public int lineNumber() { return this.lineNumber;}private int lineNumber;

}

Page 29: 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

Exceptions

Exception objects are structured as immutable objects: their interface includes no state-changing commands.

Page 30: 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

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.

Page 31: 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

Dealing with logical errors (cont.)public class PreconditionException extends

RuntimeExceptionFailure because a precondition is not satisfied.

public class Require {static public void condition (boolean precondition) { if (!precondition)

throw new PreconditionException (“Precondition not satisfied.”);

}static public void notNull (Object

reference) { if (reference == null)

throw new PreconditionException (“Null reference.”);

}}

Page 32: 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

Dealing with logical errors (cont.)/** * Interchange l.get(i) and l.get(j) * require: * 0 <= i,j < l.size() */private void interchange (List l, int i,

int j) { Require.condition(0 <= i &&

i < l.size()); Require.condition(0 <= j &&

j < l.size());…

}

Page 33: 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

Dealing with logical errors (cont.)public class PostconditionException extends

RuntimeExceptionFailure because a postcondition is not satisfied.

public class Ensure {static public void condition (boolean

postcondition){ if (!postcondition)

throw new PostconditionException (“Postcondition not satisfied.”);

}}

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.

Page 34: 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

Dealing with logical errors (cont.)public class AssertionException extends

RuntimeExceptionFailure because an assertion is not satisfied.

public class Assert {static public void condition (boolean

condition){ if (!condition)

throw new AssertionException (“Assertion not satisfied.”);

}}

Page 35: 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

Dealing with logical errors (cont.) Postconditions and invariants often are

too complex to verify with a simple condition.

Whether to include such checks depends to a large degree on where we are in the development process.

Page 36: 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

We’ve covered Method failure due to

A logical error in its implementation. Its inability to obtain some needed resource

from the environment. The exception mechanism

Detecting, reporting, handling failure. The try-catch statement. When a client is notified of a server’s failure,

the client can Attempt to correct the situation. Report failure to its caller(more practical).

Page 37: 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

Glossary