You are on page 1of 39

Software Engineering

Lecture 3:
Exception
2013

Outline
Why exception?
Java error handling mechanism
checked & unchecked exceptions

Working with exceptions


Design issues

2013

FIT330 Software Engineering

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

FIT330 Software Engineering

Example: invalid input problem


A behaviour is required for invalid input:
/**
* @effects <pre>
*
if a is sorted in ascending order
*
returns true
*
else returns false</pre>
*/
public static boolean sorted(int[] a) {
int prev = a[0];
for (int i = 1; i < a.length; i++) {
if (prev <= a[i])
prev = a[i];
else
return false;
Any problems
}
return true;
}
2013

FIT330 Software Engineering

?
4

Two common solutions


Returns a 'special' value:
error is treated part of the normal flow

Generates an special 'signal':


error is an exceptional case (separate from the
normal flow)

Which solution is better

2013

FIT330 Software Engineering

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

FIT330 Software Engineering

Solution 1's limitations


No valid special values for total procedures
Value may be ignored by caller
An additional check is always required
Returned value does not carry error details

2013

FIT330 Software Engineering

Solution 2: Exception
The special signal is called exception
no returned values needed

Caller can be forced to handle exceptions


Caller may deligate the handling
Exception is a data type that carry error details

2013

FIT330 Software Engineering

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

FIT330 Software Engineering

Java error handling mechanism


Use special 'signal'
Execution errors include:
environmental errors: derived from Error class
program errors: exceptions

New exception types can be created:


checked or unchecked

Methods are specified with exceptions

2013

FIT330 Software Engineering

10

Java exception type hierarchy


Throwable
Error

Exception
RuntimeException

(checked exceptions)

(unchecked exceptions)

2013

FIT330 Software Engineering

11

Checked vs. unchecked exception


Checked exceptions:
must be handled
derived from Exception

Unchecked exceptions:
need not be handled (automatically handled by
Java run-time)
used for code safety
subtypes of RuntimeException

2013

FIT330 Software Engineering

12

Working with exceptions


Determine the exception type
Create a new exception type
Specify a procedure with exceptions
Specify a type with exceptions
Throw an exception in the code
Handle an exception

2013

FIT330 Software Engineering

13

Determine the exception type


Types of error:
invalid input: e.g. array is null
logic: e.g. division by zero
others: e.g. disk access failure

Exception depends on the 'expectedness' of


the error:
(highly) expected: use checked exception
(mildly) unexpected: use unchecked exception

Reuse exceptions where possible


2013

FIT330 Software Engineering

14

How to name an exception?


Exception name = type of error + Exception
Examples:
array is null NullPointerException
division by zero DivideByZeroException
disk access failure DiskAccessException

2013

FIT330 Software Engineering

15

Create a new exception


Create a subtype of Exception (if checked)
or RuntimeException (if unchecked)
Placed in the same or a separate package
(better)
Implement constructor method(s):

2013

default constructor

single-argument constructor: error message

invokes suitable super constructors

Add new methods (if needed)


FIT330 Software Engineering

16

Example
public class NonPositiveException
extends RuntimeException {
public EmptyException(String msg) {
super(msg);
}
}

2013

FIT330 Software Engineering

17

Specify a proc. with exceptions


Robust procedures throw exception(s)
both checked and unchecked

Thrown exception(s) are part of the


specification
listed in the header

The @effects clause should state:


the cause of each exception
how @modifies interact with exception(s)

2013

FIT330 Software Engineering

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

FIT330 Software Engineering

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

FIT330 Software Engineering

20

Specify a type with exceptions


At least add suitable exceptions to these
operations:
constructor
setter
data validation (optional)

2013

FIT330 Software Engineering

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

FIT330 Software Engineering

22

Throw an exception
Use the throw statement
Example:
/**
* (omitted)
*/

public static int fact(int n) throws


NonPositiveException {
if (n < 0)
throw new NonPositiveException(
"fact(): input is not positive: " + n);
return ch2.Num.fact(n);
}
2013

FIT330 Software Engineering

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

A combination of the above techniques is also


common

2013

FIT330 Software Engineering

24

Example
int n = 10;
try {
int f = fact(n);
System.out.println("fact("+n+"): " + f);
} catch (NonPositiveException e) {
// handle exception
}

2013

FIT330 Software Engineering

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

FIT330 Software Engineering

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

Often used together with logging

2013

FIT330 Software Engineering

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

Typically used for serious, checked exceptions


Relected exception is the same or new:
if unchecked: reflected exception is automatically
propagated
if checked: reflected exception must be compatible
with header's

2013

FIT330 Software Engineering

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

FIT330 Software Engineering

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

Dont overuse exceptions:


excessive exception handling degrades
performance
2013

FIT330 Software Engineering

31

Overriding: header rule (review)


Inherited methods must be header compatible
Method header includes:
signature: method name, number and types of
parameters
return type
thrown exceptions (if any)

Compatibility means:
same signature
return type: same (Jdk < 1.4) or subtype (>= 1.5)

2013

exceptions: (1) subset, (2) new subtypes or


unchecked
FIT330 Software Engineering

32

Example: Vehicle TH
ch4.vehiclex.[Bus,Car]
Note:
Bus & Car constructors now throw
NotPossibleException
Such exceptions may be omitted

These constructors may throw additional run-time


exceptions

2013

FIT330 Software Engineering

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

FIT330 Software Engineering

?
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

FIT330 Software Engineering

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

FIT330 Software Engineering

36

Which part is overusing?


boolean sorted(int[] a) {
int prev;
try {
prev = a[0];
} catch (IndexOutOfBoundsException e) {
return true;
}
for (int i = 1; i < a.length; i++) {
if (prev <= a[i])
prev = a[i];
else
return false;
}
return true;
}

2013

How do you improve it


FIT330 Software Engineering

?
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

FIT330 Software Engineering

38

Questions?

2013

FIT330 Software Engineering

39