08/13/14 Võ Phương Bình - ITFAC
- DLU
1
Part IV: Developing Comprehensive
Projects
Chapter 10: Exception Handling
Chapter 11: Multithreading
Chapter 12: Multimedia
Chapter 13: Input and Output
Chapter 14: Networking
08/13/14 Võ Phương Bình - ITFAC
- DLU
2
Chapter 10
Exception Handling
What exceptions are for
What exceptions are NOT for
Catching & Throwing exceptions
Exception Specifications
Standard Java Exceptions
Exceptions and Polymorphism
The finally clause
Resource Management
Uncaught Exceptions
08/13/14 Võ Phương Bình - ITFAC
- DLU
3
What Exceptions are For
To handle Bad Things
I/O errors, other
runtime
errors
when a function fails to fulfill its
specification
so you can restore program stability (or
exit gracefully)
08/13/14 Võ Phương Bình - ITFAC
- DLU
4
What Exceptions are For, cont
To
force you
to handle Bad Things
because return codes can be tedious
and sometimes you’re lazy
08/13/14 Võ Phương Bình - ITFAC
- DLU
5
Example
File I/O
public FileReader(String fileName)
throws FileNotFoundException
public void close() throws IOException
08/13/14 Võ Phương Bình - ITFAC
- DLU
6
import java.io.*;
class OpenFile
{
public static void main(String[] args)
{
if (args.length > 0)
{
try
{
// Open a file:
FileReader f =
new FileReader(args[0]);
System.out.println(args[0]
+ " opened");
f.close();
}
catch (IOException x)
{
System.out.println(x);
}
}
}
}
Example
File I/O, cont
08/13/14 Võ Phương Bình - ITFAC
- DLU
7
What Exceptions are For, cont
To signal errors from constructors
because constructors have no return value
08/13/14 Võ Phương Bình - ITFAC
- DLU
8
What Exceptions are NOT For
NOT For Alternate Returns:
e.g., when end-of-file is reached:
while ((s = f.readLine()) != null) …
Exceptions are only for the exceptional!
08/13/14 Võ Phương Bình - ITFAC
- DLU
9
Catching Exceptions
Wrap code to be checked in a try-block
checking occurs all the way down the
execution stack
try-blocks can be nested
control resumes at most enclosed matching
handler
08/13/14 Võ Phương Bình - ITFAC
- DLU
10
Catching Exceptions, cont
Place one or more catch-clauses after try-
block
runtime system looks back up the call stack
for a matching handler
subclass types match superclass types
catching Exception catches everything (almost)
handlers are checked
in the order they
appear
place most derived types first!
execution resumes after last handler
if you let it (could branch or throw)
08/13/14 Võ Phương Bình - ITFAC
- DLU
11
Throwing Exceptions
Must throw objects derived (ultimately) from
Throwable
Usually derive from java.lang.Exception
The class name is the most important
attribute of an exception
Can optionally include a message
Provide two constructors:
MyException( )
MyException(String s)
08/13/14 Võ Phương Bình - ITFAC
- DLU
12
Throwing Exceptions, cont
Control is passed up the execution
stack to a matching handler
Various methods exist for processing
exceptions:
getMessage( )
toString( ) (class name + message)
printStackTrace( )
08/13/14 Võ Phương Bình - ITFAC
- DLU
13
Throwing Exceptions, cont
Functions must “advertise” their
exceptions
every function must specify the “checked”
exceptions it (or its callees!) may throw
Callers must do one of two things:
handle your exceptions with try-catch, or
advertise your exceptions along with theirs
08/13/14 Võ Phương Bình - ITFAC
- DLU
14
Sample Program
FixedStack
implements a stack with an array of Object
various methods throw exceptions
class StackException
StackTest
must handle StackExceptions
08/13/14 Võ Phương Bình - ITFAC
- DLU
15
class StackException extends Exception
{
StackException()
{}
StackException(String msg)
{
super(msg);
}
}
Sample Program, cont
Sample Program, cont
08/13/14 Võ Phương Bình - ITFAC
- DLU
16
class FixedStack
{
private int capacity;
private int size;
private Object[] data;
public FixedStack(int cap)
{
data = new Object[cap];
capacity = cap;
size = 0;
}
public void push(Object o)
throws StackException
{
if (size == capacity)
throw new StackException("overflow");
data[size++] = o;
}
Sample Program, cont
Sample Program, cont
08/13/14 Võ Phương Bình - ITFAC
- DLU
17
public Object pop()
throws StackException
{
if (size <= 0)
throw new StackException("underflow");
return data[ size];
}
public Object top()
throws StackException
{
if (size <= 0)
throw new StackException("underflow");
return data[size-1];
}
public int size()
{
return this.size;
}
}
Sample Program, cont
Sample Program, cont
08/13/14 Võ Phương Bình - ITFAC
- DLU
18
class StackTest
{
public static void main(String[] args)
{
FixedStack s = new FixedStack(3);
doTest(s);
}
public static void doTest(FixedStack s)
{
try
{
System.out.println("Initial size = "
+ s.size());
s.push("one");
s.push(new Integer(2));
s.push(new Float(3.0));
s.push("one too many"); // error!
}
catch(StackException x)
{
System.out.println(x);
}
Sample Program, cont
Sample Program, cont
08/13/14 Võ Phương Bình - ITFAC
- DLU
19
try
{
System.out.println("Top: " + s.top());
System.out.println("Popping ");
while (s.size() > 0)
System.out.println(s.pop());
}
catch(StackException x)
{
throw new InternalError(x.toString());
}
}
}
/* Output:
Initial size = 0
StackException: overflow
Top: 3.0
Popping
3.0
2
one
*/
Sample Program, cont
Sample Program, cont
08/13/14 Võ Phương Bình - ITFAC
- DLU
20
Using printStackTrace( )
catch(StackException x)
{
x.printStackTrace(System.out);
}
…
StackException: overflow
at FixedStack.push(FixedStack.java:18)
at StackTest.doTest(StackTest.java, Compiled Code)
at StackTest.main(StackTest.java:6)
08/13/14 Võ Phương Bình - ITFAC
- DLU
21
Standard Java Exceptions
Throwable
Exception Error
RuntimeException
IOException
. . .
08/13/14 Võ Phương Bình - ITFAC
- DLU
22
Class java.lang.Exception
The one you usually derive from
“Checked Exceptions”
specifications checked at
compile
time
you must either catch or advertise these
Used for recoverable errors
Not programmer errors
08/13/14 Võ Phương Bình - ITFAC
- DLU
23
java.lang.Exception Subclasses
AWTException
ClassNotFoundException
CloneNotSupportedException
IOException
NoSuchFieldException
08/13/14 Võ Phương Bình - ITFAC
- DLU
24
Class java.lang.Error
For JVM Failures and other Weird
Things
let program terminate
InternalError is one of these
Don’t catch them
you don’t know what to do!
These are “unchecked exceptions”
not required to advertise
08/13/14 Võ Phương Bình - ITFAC
- DLU
25
java.lang.Error Subclasses
AWTError
LinkageError
…
ThreadDeath
VirtualMachineError
InternalError, OutOfMemoryError,
StackOverflowError, UnknownError