All Java exceptions are instances of classes in the Exception class hierarchy. This can be represented as follows:
java.lang.Throwable
- This is the base class for all exception classes. Its methods and constructors implement a range of functionality common to all exceptions.
java.lang.Exception
- This is the superclass of all normal exceptions.
java.lang.RuntimeException
- This the superclass of all normal exceptions that are unchecked exceptions.
java.lang.Error
- This is the superclass of all "fatal error" exceptions.Notes:
Throwable
, Exception
and RuntimeException
class should be treated as abstract
; see Pitfall - Throwing Throwable, Exception, Error or RuntimeException.Error
exceptions are thrown by the JVM in situations where it would be unsafe or unwise for an application to attempt to recover.Throwable
. Java tools and libraries may assume that Error
and Exception
are the only direct subtypes of Throwable
, and misbehave if that assumption is incorrect.One of the criticisms of exception support in some programming languages is that is difficult to know which exceptions a given method or procedure might throw. Given that an unhandled exception is liable to cause a program to crash, this can make exceptions a source of fragility.
The Java language addresses this concern with the checked exception mechanism. First, Java classifies exceptions into two categories:
Checked exceptions typically represent anticipated events that an application should be able to deal with. For instance, IOException
and its subtypes represent error conditions that can occur in I/O operations. Examples include, file opens failing because a file or directory does not exist, network reads and writes failing because a network connection has been broken and so on.
Unchecked exceptions typically represent unanticipated events that an application cannot deal with. These are typically the result of a bug in the application.
(In the following, "thrown" refers to any exception thrown explicitly (by a throw
statement), or implicitly (in a failed dereference, type cast and so on). Similarly, "propagated" refers to an exception that was thrown in a nested call, and not caught within that call. The sample code below will illustrate this.)
The second part of the checked exception mechanism is that there are restrictions on methods where a checked exception may occur:
throws
clause. (The significance of the throws
clause is described in this example.)In short, a checked exception must be either handled, or declared.
These restrictions do not apply to unchecked exceptions. This includes all cases where an exception is thrown implicitly, since all such cases throw unchecked exceptions.
These code snippets are intended to illustrate the checked exception restrictions. In each case, we show a version of the code with a compilation error, and a second version with the error corrected.
// This declares a custom checked exception.
public class MyException extends Exception {
// constructors omitted.
}
// This declares a custom unchecked exception.
public class MyException2 extends RuntimeException {
// constructors omitted.
}
The first example shows how explicitly thrown checked exceptions can be declared as "thrown" if they should not be handled in the method.
// INCORRECT
public void methodThrowingCheckedException(boolean flag) {
int i = 1 / 0; // Compiles OK, throws ArithmeticException
if (flag) {
throw new MyException(); // Compilation error
} else {
throw new MyException2(); // Compiles OK
}
}
// CORRECTED
public void methodThrowingCheckedException(boolean flag) throws MyException {
int i = 1 / 0; // Compiles OK, throws ArithmeticException
if (flag) {
throw new MyException(); // Compilation error
} else {
throw new MyException2(); // Compiles OK
}
}
The second example shows how a propagated checked exception can be dealt with.
// INCORRECT
public void methodWithPropagatedCheckedException() {
InputStream is = new FileInputStream("someFile.txt"); // Compilation error
// FileInputStream throws IOException or a subclass if the file cannot
// be opened. IOException is a checked exception.
...
}
// CORRECTED (Version A)
public void methodWithPropagatedCheckedException() throws IOException {
InputStream is = new FileInputStream("someFile.txt");
...
}
// CORRECTED (Version B)
public void methodWithPropagatedCheckedException() {
try {
InputStream is = new FileInputStream("someFile.txt");
...
} catch (IOException ex) {
System.out.println("Cannot open file: " + ex.getMessage());
}
}
The final example shows how to deal with a checked exception in a static field initializer.
// INCORRECT
public class Test {
private static final InputStream is =
new FileInputStream("someFile.txt"); // Compilation error
}
// CORRECTED
public class Test {
private static final InputStream is;
static {
InputStream tmp = null;
try {
tmp = new FileInputStream("someFile.txt");
} catch (IOException ex) {
System.out.println("Cannot open file: " + ex.getMessage());
}
is = tmp;
}
}
Note that in this last case, we also have to deal with the problems that is
cannot be assigned to more than once, and yet also has to be assigned to, even in the case of an exception.