Transcript Exceptions

Exceptions
•
•
•
•
•
•
•
The Need for Exceptions
Throwing Exceptions
Exception Objects
Object Construction Failure
Catching Exceptions
The Error Exception
The Finally Clause
OOP with Java, David
J. Barnes
Exceptions
1
The Need For Exceptions
• ''The World Outside'' is potentially hostile.
• A public interface allows external access.
• Possible exceptional conditions:
– Trying to move a ship that is moored.
– Trying to book a seat in a full theatre.
– Going faster than the local speed limit.
• The exceptional condition is based on the Ship's
context, rather than its state.
OOP with Java, David
J. Barnes
Exceptions
2
Possible Responses
•
•
•
•
•
•
•
•
Print an error message.
Terminate the program.
Silently ignore the request.
Implement the request anyway.
Implement a modified or faked action.
Request a correction interactively.
Return the wrong answer.
Return an error indication.
OOP with Java, David
J. Barnes
Exceptions
3
Throwing an Exception
• Java's standard 'error indication' is an
exception.
• Each is represented by an Exception object.
– ArithmeticException.
– ArrayIndexOutOfBoundsException.
– ClassCastException.
– NumberFormatException.
OOP with Java, David
J. Barnes
Exceptions
4
The Throw Statement
class UncheckedMain2 {
public static void main(String[] args){
// Terminate the whole program.
throw new RuntimeException(
"I just can't cope!");
}
}
Exception in thread "main" java.lang.RuntimeException:
I just can't cope!
at java.lang.Throwable.<init>(Throwable.java:78)
at java.lang.Exception.<init>(Exception.java:42)
at java.lang.RuntimeException.<init>(RuntimeException.java:47)
at UncheckedMain2.main(UncheckedMain2.java:4)
OOP with Java, David
J. Barnes
Exceptions
5
Exception Objects
• Exception objects have methods.
– public String getMessage();
– public void printStackTrace();
– public String toString();
• These methods are used when an exception
is caught, to provide diagnostic information.
OOP with Java, David
J. Barnes
Exceptions
6
The Throws Clause
public void setSpeed(double s) throws RuntimeException {
// Check the validity of the request.
if(Math.abs(s) > maximumSpeed){
// Too fast. Don't proceed.
throw new RuntimeException("Speed "+s+
" is beyond the maximum of "+
maximumSpeed);
}
else{
speed = s;
}
}
OOP with Java, David
J. Barnes
Exceptions
7
Object Construction Failure
class Circle {
public Circle(double r) throws RuntimeException {
if(r <= 0){
throw new RuntimeException(
"The radius must be positive: "+r);
}
radius = r;
}
...
}
OOP with Java, David
J. Barnes
Exceptions
8
Checked Exceptions
• RuntimeException is an unchecked
exception.
– Unchecked do not require a throws clause.
– Unchecked do not have to be 'caught'.
• Exception is a checked exception.
– Checked do require a throws clause.
– Checked do have to be dealt with in some way.
OOP with Java, David
J. Barnes
Exceptions
9
Catching Exceptions
• An exception that is not caught or handled
will result in immediate program failure.
• Catching an exception means we might be
able to fix the problem.
– Try a slower speed for the ship.
• Java's try statement provides an exception
handling (catching) mechanism.
OOP with Java, David
J. Barnes
Exceptions
10
The Try Statement
try{
// Things could go wrong within this block.
statement;
...
}
catch(Exception e){
// Something went wrong.
statement;
...
}
finally{
statement;
...
}
OOP with Java, David
J. Barnes
Exceptions
11
Catching an Exception
try{
// Construction could fail.
Ship argo = new Ship();
double speed = ...;
...
// Setting a new speed could fail.
argo.setSpeed(speed);
...
}
catch(RuntimeException e){
System.err.println(e.getMessage());
}
OOP with Java, David
J. Barnes
Exceptions
12
Anticipating Multiple Exceptions
try{
// The protected statements.
...
}
catch(IndexOutOfBoundsException e){
...
}
catch(ArithmeticException e){
...
}
catch(RuntimeException e){
...
}
OOP with Java, David
J. Barnes
Exceptions
13
Propagating Exceptions
• The rules for checked and unchecked
exceptions differ.
• Unchecked exceptions.
– Propagated to the caller if there is no local
caller.
• Checked exceptions.
– Must be handled locally, or propagated via an
explicit throws clause.
OOP with Java, David
J. Barnes
Exceptions
14
Rethrowing an Exception
public void method() throws Exception {
try{
// Protected statements
...
}
catch(Exception e){
// Partial recovery.
...
// Rethrow the exception.
throw e;
}
}
OOP with Java, David
J. Barnes
Exceptions
15
The Error Exception
• The java.lang package defines Error
as representing a particularly serious
exception.
– One from which recovery is impossible.
– For instance, an out-of-memory problem.
• Use sparingly, and as a last resort.
– Anticipate exceptions, and plan for their
recovery.
OOP with Java, David
J. Barnes
Exceptions
16
The Finally Clause
public void method(){
try{
// T2 might throw an exception.
Statement-T1;
Statement-T2;
Statement-T3;
}
catch(Exception e){
Statement-C;
}
finally{
Statement-F;
}
}
OOP with Java, David
J. Barnes
Exceptions
17
Often Used to Close Files
FileReader inFile = null;
FileWriter outFile = null;
try{
inFile = new FileReader(source);
outFile = new FileWriter(destination,true);
...
}
finally{
if(inFile != null){
inFile.close();
}
if(outFile != null){
outFile.close();
}
}
OOP with Java, David
J. Barnes
Exceptions
18
Review
• An object might be asked to perform
inappropriate actions.
• An object often does not know how to
respond in such situations.
• Exceptions allow an object to leave the caller
to sort out the problem.
• An exception is either checked or unchecked.
OOP with Java, David
J. Barnes
Exceptions
19
Review (cont.)
• Exceptions may be caught and handled, or
propagated.
• Uncaught (unhandled) exceptions result in
premature program termination.
• The finally clause provides an alwaysexecuted route out of a try statement.
• Either the catch clause or finally clause may
be omitted.
OOP with Java, David
J. Barnes
Exceptions
20