Saturday, June 30, 2007
Leaking Exceptions in Java
The try/finally block in Java can leak exceptions due to programming errors. The examples from Bruce Eckel's Thinking In Java (a gem of a book on Java) demonstrates how this part is broken in Java if programmer is not careful:
yet another example of how exceptions can be lost:
public class ExceptionSilencer {
public static void main(String[] args) {
try {
throw new RuntimeException();
} finally {
// Using 'return' inside the finally block
// will silence any thrown exception.
return;
}
}
}
yet another example of how exceptions can be lost:
class VeryImportantException extends Exception {
public String toString() {
return "A very important exception!";
}
}
class HoHumException extends Exception {
public String toString() {
return "A trivial exception";
}
}
public class LostMessage {
void f() throws VeryImportantException {
throw new VeryImportantException();
}
void dispose() throws HoHumException {
throw new HoHumException();
}
public static void main(String[] args) {
try {
LostMessage lm = new LostMessage();
try {
lm.f();
} finally {
lm.dispose();
}
} catch(Exception e) {
System.out.println(e);
}
}
}