Error Handling with Exceptions
Exception
Handling
Badly-formed code will not
be run.
Not all errors can be
caught at compile time.
Runtime error handling
integrated into the core of
the language, enforced by
the compiler.
Throwing an Exception
Exception Handling
Exception Specification
Inheritance
Software Systems Institute
2004/2005
http://www.sts.tu-harburg.de
LTOOD-STS-Overview and Language Fundamentals
Basic Exceptions
Catching an Exception
Exceptional Condition : not enough info in the current
context to continue processing
throw an exception:
The try block: a guarded region
try {
// code that may generate exceptions
}
if (t == null)
throw new NullPointerException();
Exception arguments
if (t == null)
throw new NullPointerException("t= null");
I think I can...
I think I can...
Like any other constructor
Info can be extracted later
LTOOD-STS-Overview and Language Fundamentals
Exceptional Condition : not enough info in the current
context to continue processing
LTOOD-STS-Overview and Language Fundamentals
Exception Handlers
Catching any Exception
try {
// code that may generate exceptions
} catch(Type1 id1) {
// handle exceptions of Type1
} catch(Type2 id2) {
// handle exceptions of Type2
} catch(Type3 id3) {
// handle exceptions of Type3
}
All exceptions derived from root class Exception
catch(Exception e) {
System.out.println("caught an exception");
}
For special Class RuntimeException and
subclasses handling not enforced
// etc...
LTOOD-STS-Overview and Language Fundamentals
LTOOD-STS-Overview and Language Fundamentals
1.2.1
The Exception Specification
Inheritance of Exceptions
void f() throws TooBigException { //...
If base-class method throws an exception, derivedclass method may throw that exception or one
derived from it.
If you say
void f() {}
It means that no exceptions (except for those derived
from the special class RuntimeException) may be
thrown.
Compiler verifies exception specifications!
This guarantees that all exceptions will get
caught somewhere.
LTOOD-STS-Overview and Language Fundamentals
Derived-class method cannot throw an exception that
isnt a type/subtype of an exception thrown by the
base-class method.
class CarException extends Exception {}
class Stolen extends CarException {}
class NoGasoline extends CarException {}
abstract class Car {
void stop() throws CarException {
// ...
throw new CarException();
}
abstract void start() throws Stolen, NoGasoline;
}
class BadWeather extends CarException {}
class NoSpecialGasoline extends NoGasoline {}
public class SportsCar extends Car {
void stop() throws BadWeather { /* */ }
Cant throw
void start() throws NoSpecialGasoline{ /* ... */}
BadWeather
public static void main(String args[]) {
SportsCar sc = new SportsCar();
try {
sc.start();
} catch(NoSpecialGasoline e) { }
}
}
LTOOD-STS-Overview and Language Fundamentals
Exception Matching
Base-class handler will catch derived-class object
class AnnoyanceException extends Exception {}
class SneezeException extends AnnoyanceException {}
public class Human {
public static void main(String args[]) {
try {
...
throw new SneezeException();
} catch(SneezeException s) {
System.out.println("Caught Sneeze");
} catch(AnnoyanceException a) {
System.out.println("Caught Annoyance");
}
}
}
Creating Your Own Exceptions
LTOOD-STS-Overview and Language Fundamentals
10
Primitive exception handling
class MyException extends Exception {
public MyException() {}
public MyException(String msg) {
super(msg);
}
}
public static void main(String args[]) {
// ... create object o etc.
try {
o.f();
} catch(MyException e) {
e.printStackTrace();
// hierarchy of method calls which led to exception
}
try {
o.g();
} catch(MyException e) {
// do nothing at all, just catch exception
}
}
}
public class Inheriting {
public void f() throws MyException {
System.out.println("Throwing MyException from f()");
throw new MyException();
}
public void g() throws MyException {
System.out.println("Throwing MyException from g()");
throw new MyException("Originated in g()");
}
}
LTOOD-STS-Overview and Language Fundamentals
LTOOD-STS-Overview and Language Fundamentals
11
LTOOD-STS-Overview and Language Fundamentals
12
1.2.2
Constructors and Exceptions
Whats in a name?
Cannot have anything before base-class constructor
call, not even a try block
Exceptions of Base Class Constructor must be
shown in derived-class exception specification.
Name of the exception is typically the most important
thing about it.
Names tend to be long and descriptive.
Code for the exception class itself is usually minimal.
Once you catch the exception you typically are done
with it.
abstract class Car {
Car() throws NoGasoline {}
...
}
NoGasoline
public class SportsCar extends Car {
may not be
SportsCar()throws NoGasoline, Stolen {
replaced by
// super() inserted by compiler
NoSpecialGasoline!
...
}
LTOOD-STS-Overview and Language Fundamentals
13
LTOOD-STS-Overview and Language Fundamentals
Rethrowing an Exception
Methods of class Exception
catch(Exception e) {
System.out.println("An exception was thrown");
throw e;
// throw e.fillInStackTrace();
}
Fairly minimal:
public class ExceptionMethods {
public static void main(String args[]) {
try {
throw new Exception("Here's my Exception");
} catch(Exception e) {
System.out.println("Caught Exception");
System.out.println(
"e.getMessage(): " + e.getMessage());
System.out.println("e.toString(): " + e.toString());
System.out.println("e.printStackTrace():");
e.printStackTrace();
}
}
}
Perform anything you can locally, then let a global handler
perform more appropriate activities
fillInStackTrace records within this throwable object
information about the current state of the stack frames for the
current thread.
LTOOD-STS-Overview and Language Fundamentals
15
Output:
LTOOD-STS-Overview and Language Fundamentals
16
Performing Cleanup with finally
Caught Exception
e.getMessage(): Here's my Exception
e.toString(): java.lang.Exception: Here's my Exception
e.printStackTrace() :
java.lang.Exception: Here's my Exception
at ExceptionMethods. main
LTOOD-STS-Overview and Language Fundamentals
14
try {
// The guarded region:
// Dangerous activities that
// may throw A, B, or C
} catch (A a1) {
// Handle A
} catch (B b1) {
// Handle B
} catch (C c1) {
// Handle C
} finally {
// Actions that happen every time
}
17
LTOOD-STS-Overview and Language Fundamentals
18
1.2.3
public class Test {
Whats finally for?
public static void main(String args[]) {
Switch sw = new Switch();
try {
sw.on();
// code that may throw exceptions...
sw.off();
} catch(NullPointerException e) {
System.out.println("NullPointerException");
sw.off();
} catch(IOException e) {
System.out.println("IOException");
sw.off();
}
}
Always gets called, regardless of what happens with
the exception and where its caught
To set something other than memory back to its
original state (GC handles memory)
class Switch {
boolean state = false;
boolean read() { return state; }
void on() { state = true; }
void off() { state = false; }
}
}
Doesnt always work... & cleanup code is duplicated
LTOOD-STS-Overview and Language Fundamentals
19
LTOOD-STS-Overview and Language Fundamentals
20
public class TestWithFinally {
Exceptions Summary
public static void main(String args[]) {
Switch sw = new Switch();
try {
sw.on();
// code that may throw exceptions...
} catch(NullPointerException e) {
System.out.println("NullPointerException");
} catch(IOException e) {
System.out.println("IOException");
} finally {
sw.off();
}
}
You have no choice in Java
You must catch exceptions
You must use exception specifications
The compiler enforces exception use
A clean, straightforward error-handling model
You dont have to decide how to handle errors
You dont have to figure out how someone else
handles errors
You dont worry about whether errors get handled
You have to be careful about exception handling and
inheritance
Always works!
LTOOD-STS-Overview and Language Fundamentals
21
LTOOD-STS-Overview and Language Fundamentals
22
Exercises
Write a class that opens a text file and prints the
content.
the name of the textfile should be read of the
console
use sun API documentation
hints:
BufferedReader
FileReader
InputStreamReader
System.out.println
LTOOD-STS-Overview and Language Fundamentals
23
1.2.4