Transcript Chapter 17

Chapter 17
Failures and exceptions
This chapter discusses







Failure.
The meaning of system failure.
Causes of failure.
Handling failure.
Exception mechanism.
Using Exception class and its
subclasses.
Generating exceptions.
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.
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.
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.
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.
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.
The Java exception
mechanism (cont.)
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.
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.
The Java exception
mechanism (cont.)
Catching exceptions
try {
statements1
} catch ( exception parameter1 ) {
statements2
} catch ( exception parameter2 ) {
statements3
} …
Catching exceptions
(cont.)
try {
statements1
} catch ( ArithmeticExection e) {
statements2
} catch ( NullPointerException e ) {
statements3
} catch ( Exception e ) {
statements4
}
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.

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);
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.
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.
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)
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.
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.

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.

FileReader example

A class java.io.FileReader constructor is
specified as follows.
public FileReader (String fileName) throws
FileNotFoundException, SecurityException

is an unchecked
exception, but is something we wish to
address.
SecurityException
public void getSomeData() throws
FileNotFoundException,SecurityException{
FileReader in;
in = new FileReader (“DataFile”);
…
}
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;
}
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.
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 opened
int tryNumber = 0;//# of attempts to open datafile
int delay = 5 * 1000;//wait in millsecs
while (!success)
try {
tryNumber = tryNumber + 1;
in = new FileReader(“DataFile”);
success = true;
…
} catch (SecurityException e) {
if (tryNumber == 1)
thisThread.sleep(delay);
else
throw e;
}
}
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);
}
}
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”);
}
}
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;
}
Exceptions

Exception objects are structured as
immutable objects: their interface
includes no state-changing commands.
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.
Dealing with logical
errors (cont.)
public class PreconditionException extends
RuntimeException
Failure 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.”);
}
}
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());
…
}
Dealing with logical
errors (cont.)
public class PostconditionException extends
RuntimeException
Failure 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.
Dealing with logical
errors (cont.)
public class AssertionException extends
RuntimeException
Failure because an assertion is not
satisfied.
public class Assert {
static public void condition (boolean
condition){
if (!condition)
throw new AssertionException
(“Assertion not satisfied.”);
}
}
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.
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).

Glossary