Back to the main page
Exceptions may be either checked or unchecked. The compiler will report an error if checked exceptions are not handled.
Overridden methods
Subclasses can not override methods that throw exceptions with methods throwing superclasses of the exceptions instead, neither can an overriding method remove the throws exception. The throws exception clause can only be made more specific not more generic.
Catch clauses need to be in hierarchical order, with the more specific subclass exceptions listed before the more generic superclass exceptions
class ParentException extends Exception {}
class ChildException extends ParentException {}
class GrandChildException extends ChildException {}
class Superclass {
void myMethod() throws ParentException {
if (true) {
throw new ChildException();
}
}
}
class Subclass extends Superclass {
void myMethod() throws ChildException {
if (true) {
throw new GrandChildException();
}
}
}
public class Handling {
public static void main(String[] args) {
try {
Subclass s = new Subclass();
s.myMethod();
}
catch(GrandChildException e) {
System.out.println(e);
throw new RuntimeException("test");
}
catch(ChildException e) {
System.out.println(e);
}
catch(RuntimeException e) {
System.out.println(e);
}
finally {
System.out.println("finally");
}
}
}
Exceptions thrown from inside catch clauses will not be caught by other catch clauses of the same try...catch block but instead be thrown up and out of the try...catch block. Try...catch blocks can be nested inside try, catch or finally blocks.
Output from running the code above.
> java Handling
GrandChildException
finally
Exception in thread "main" java.lang.RuntimeException: test
at Handling.main(Handling.java:29)
If an exception is thrown from the try block and there are no catch blocks to catch it and then a second exception is thrown from within the finally block, or an exception is thrown from a catch block, it is this second exception that is ultimately thrown from the try...catch...finally clause effectively making the first exception disappear.
Try with resources
From Java 7 onwards.
Variables may be declared inside parentheses immediately after the try keyword. Any such resources must implement the java.lang.AutoClosable interface which has just one method close(); which is called once the try block has completed, even if an exception has been thrown. This is less verbose than placing a call to close() for each of the variables inside a finally block.
try(FileInputStream fi = new FileInputStream("file.txt");
BufferedInputStream bi = new BufferedInputStream(fi)) {
// ...
}
Multiple exception catch block
From Java 7 onwards.
Catch blocks can be defined to catch more than one type of exception.
try {
// ...
}
catch(IOException | MyOwnException e) {
// ...
}