Java Slides

advertisement
Java Exceptions
SWE 332
Last Modified Spring 2010
Paul Ammann
Rationale for Exceptions

Preconditions document undefined behavior


Undefined behavior  Partial specification
In any implementation, something happens

Should clients rely on undocumented behavior?


Bottom line:

Preconditions are usually undesirable


What happens in next release?
But sometimes unavoidable…
Exception handling:


Transform preconditions to defined behavior
One of several possible mechanisms…
2
Transforming a Precondition to
an Exceptional Postcondition
Key: Postcondition defines behavior for inputs excluded by precondition
public double sqrt (double x)
// precondition: x >= 0
// postcondition: …
public double sqrt (double x)
// precondition:
// postcondition: If x < 0 throw IllegalArgumentException
// else …
public double sqrt (double x)
/**
* @param x the square of the intended result
* @return approximate square root of x…
* @throws IllegalArgumentException if x < 0
*/
3
Java Exception Mechanism
Throwable
Error
Exception
…
RuntimeException
Checked Exceptions
…
Unchecked Exceptions
Ammann 2008
4
Exceptions




Unchecked: client does not need to
explicitly write special code
Checked: client has to pay attention to
these. Must write special code blocks
Many different types of exceptions are
provided.
You can provide your own.
Ammann 2008
5
Custom Exceptions
public MyFavoriteException extends Exception {
public MyFavoriteException() {
super();
}
public MyFavoriteException(String s) {super(s);}


can add more
like state at the time of throwing the exception
methods that let the invalid state be printed and other useful
information
Ammann 2008
6
Throwing Exceptions



Explicit throws
throw new NullPointerException(“”);
throw new NPE(“class, method”);
System throws
String [ ] a = {“1”,”2”,”3”,”4”,”5”};
print(a[-1]);
System throws IndexOutOfBoundsException
Passing through (goes up the call chain)

keeps going till it finds a handler
Ammann 2008
7
Catching Exceptions

In a special code block called try-block
try{
}catch(ExceptionType instance){
}
Ammann 2008
8
Catching Exceptions


Can have multiple catch blocks, with
different execution logic for different
exceptions raised
Class hierarchy matters in catching!


If you catch an exception of type
Exception, all subtypes are also caught!
catching Exception is dangerous! WHY?
Ammann 2008
9
Remember!


try-catch block should be as short as
possible.
catch the right type of exception: to be
sure of what’s the right thing to do
Ammann 2008
10
Download