Professional Documents
Culture Documents
Lecture 3:
Exception
2013
Outline
Why exception?
Java error handling mechanism
checked & unchecked exceptions
2013
Why exception?
Problem: how to design robust procedures
i.e. behave in a well-defined way when errors
occur
Requirements:
not to terminate abruptly
provides an approximation of the normal behaviour
2013
?
4
2013
Solution 1 example
public static boolean sorted(int[] a) {
if (a == null)
return false;
if (a.length<=1)
return true;
int prev = a[0];
for (int i = 1; i < a.length; i++) {
if (prev <= a[i])
prev = a[i];
else
return false;
}
return true;
}
2013
2013
Solution 2: Exception
The special signal is called exception
no returned values needed
2013
Solution 2 example
public static boolean sorted(int[] a)
throws NullPointerException {
if (a == null)
throw new NullPointerException("sorted: array is null");
if (a.length<=1)
return true;
int prev = a[0];
for (int i = 1; i < a.length; i++) {
if (prev <= a[i])
prev = a[i];
else
return false;
}
return true;
}
2013
2013
10
Exception
RuntimeException
(checked exceptions)
(unchecked exceptions)
2013
11
Unchecked exceptions:
need not be handled (automatically handled by
Java run-time)
used for code safety
subtypes of RuntimeException
2013
12
2013
13
14
2013
15
2013
default constructor
16
Example
public class NonPositiveException
extends RuntimeException {
public EmptyException(String msg) {
super(msg);
}
}
2013
17
2013
18
Example: fact
/**
* @effects <pre>
*
if n is non-positive,
*
throws NonPositiveException
*
else
*
returns the factorial of n</pre>
*/
public static int fact(int n) throws NonPositiveException
2013
19
search
/**
* @requires <tt>a</tt> is sorted
* @effects
<pre>
*
if a is null
*
throws NullPointerException
*
else if x is not in a
*
throws NotFoundException
*
else
*
returns i such that a[i] = x</pre>.
*/
public static int search(int[] a, int x)
throws NullPointerException, NotFoundException
2013
20
2013
21
Example: Vehicle
ch4.vehiclex.Vehicle
Note:
Vehicle throws NotPossibleException in
constructor and setters
Vehicle implements Comparable and provides
an implementation for compareTo:
compareByName: throws two run-time exceptions
2013
22
Throw an exception
Use the throw statement
Example:
/**
* (omitted)
*/
23
Handle an exception
Specify in throws or handle in the code
Surrounds the using code with try...catch
Three techniques applied to the catch block:
Logging
Masking
Reflecting
2013
24
Example
int n = 10;
try {
int f = fact(n);
System.out.println("fact("+n+"): " + f);
} catch (NonPositiveException e) {
// handle exception
}
2013
25
Log an exception
Record the exception details (e.g. to file)
Example:
int n = 10;
try {
int f = fact(n);
System.out.println("fact("+n+"): " + f);
} catch (NonPositiveException e) {
// should not happen, log
System.err.println("Error: invalid input " +
e.getMessage());
// more details
// e.printStackTrace();
}
2013
26
Mask an exception
When exceptions are expected as part of the
logic
Handles the exception to terminate normally
(if required) return an exceptional value
2013
27
Example
/**
* @effects <pre>
*
if n is non-positive
*
log error and return -1
*
else
*
return the factorial of n</pre>
*/
public static int computeFact1(int n) {
try {
int f = fact(n);
return f;
} catch (NonPositiveException e) {
// log
System.err.println("Error: invalid input " +
e.getMessage());
// mask using -1
return -1;
}
}
2013
FIT330 Software Engineering
28
Reflect an exception
Propagates an exception up to the caller:
deligate the handling
2013
29
Reflection example
/**
* @effects <pre>
*
if n is non-positive
*
throw NotPossibleException
*
else
*
return the factorial of n</pre>
*/
public static void computeFact2(int n)
throws NotPossibleException {
try {
int f = fact(n);
System.out.println("fact("+n+"): " + f);
} catch (NonPositiveException e) {
throw new NotPossibleException(
"Could not compute fact("+n+")");
}
}
2013
30
Design issues
Method overriding with exceptions
Reuse exceptions where possible
Consider the context of use:
partial procedures may use special values
total procedures need exceptions to define
behaviour for all inputs
31
Compatibility means:
same signature
return type: same (Jdk < 1.4) or subtype (>= 1.5)
2013
32
Example: Vehicle TH
ch4.vehiclex.[Bus,Car]
Note:
Bus & Car constructors now throw
NotPossibleException
Such exceptions may be omitted
2013
33
Partial procedure
/**
* @requires <tt>a != null</tt>
* @effects
*
<pre>
*
if a is sorted in ascending order
*
return true
*
else
*
return false</pre>
*/
boolean sorted(int[] a)
Why no exceptions
2013
?
34
Total procedure
/**
* @effects
*
<pre>if a is null
*
throws NullPointerException
*
else if a is sorted in asc order
*
return true
*
else return false</pre>
*/
public static boolean sorted(int[] a)
throws NullPointerException
2013
35
Overuse example
/**
* @requires <tt>a != null</tt>
* @effects
*
<pre>
*
if a is sorted in ascending order
*
return true
*
else
*
return false</pre>
*/
boolean sorted(int[] a)
2013
36
2013
?
37
Summary
Exceptions are needed in robust programs
Exceptions can be checked or unchecked
Procedures/operations are specified with
exceptions
Implementations must throw the specified
exceptions
Exceptions are handled in the code by a
combination of logging and masking or
reflecting
2013
38
Questions?
2013
39