Exception handling in Java Java 07.02.2014

An exception is an anomalous condition that alters or interrupts the flow of execution. Java provides built-in exception handling to deal with such conditions. Exception handling should not be part of the normal program flow.

All exceptions and errors inherit from the class Throwable, which inherits from the class Object.

java_exception_hierarchy.png

Exceptions and errors fall into three categories: checked exceptions, unchecked exceptions, and errors.

Checked Exceptions

  • Checked exceptions are checked by the compiler at compile time.
  • Methods that throw a checked exception must indicate so in the method declaration using the throws clause. This must continue all the way up the calling stack until the exception is handled.
  • All checked exceptions must be explicitly caught with a catch block.
  • Checked exceptions include exceptions of the type Exception, and all classes that are subtypes of Exception, except for RuntimeException and the subtypes of RuntimeException.

The following is an example of a method that throws a checked exception:

// method declaration that throws an IOException
void readFile(String filename) throws IOException {
    ...
}

Common Checked exceptions:

  • ClassNotFoundException. Thrown when a class cannot be loaded because its definition cannot be found.
  • IOException. Thrown when a failed or interrupted operation occurs. Two common subtypes of IOException are EOFException and FileNotFoundException.
  • FileNotFoundException. Thrown when an attempt is made to open a file that cannot be found.
  • SQLException. Thrown when there is a database error.
  • InterruptedException. Thrown when a thread is interrupted.
  • NoSuchMethodException. Thrown when a called method cannot be found.
  • CloneNotSupportedException. Thrown when clone() is called by an object that is not cloneable.

Unchecked Exceptions

  • The compiler does not check unchecked exceptions at compile time.
  • Unchecked exceptions occur during runtime due to programmer error (e.g., out-of-bounds index, divide by zero, and null pointer exception) or system resource exhaustion.
  • Unchecked exceptions do not have to be caught.
  • Methods that may throw an unchecked exception do not have to (but can) indicate this in the method declaration.
  • Unchecked exceptions include exceptions of the type RuntimeException and all subtypes of RuntimeException.

Common Unchecked exceptions:

  • ArithmeticException. Thrown to indicate that an exceptional arithmetic condition has occurred.
  • ArrayIndexOutOfBoundsException. Thrown to indicate an index is out of range.
  • ClassCastException. Thrown to indicate an attempt to cast an object to a subclass of which it is not an instance.
  • DateTimeException. Thrown to indicate problems with creating, querying, and manipulating date-time objects.
  • IllegalArgumentException. Thrown to indicate that an invalid argument has been passed to a method.
  • IllegalStateException. Thrown to indicate that a method has been called at an inappropriate time.
  • IndexOutOfBoundsException. Thrown to indicate that an index is out of range.
  • NullPointerException. Thrown when code references a null object but a nonnull object is required.
  • NumberFormatException. Thrown to indicate an invalid attempt to convert a string to a numeric type.
  • UncheckedIOException. Wraps an IOException with an unchecked exception.

Errors

  • Errors are typically unrecoverable and present serious conditions.
  • Errors are not checked at compile time and do not have to be (but can be) caught/handled.

Common Errors:

  • AssertionError. Thrown to indicate that an assertion failed.
  • ExceptionInInitializeError. Thrown to indicate an unexpected exception in a static initializer.
  • VirtualMachineError. Thrown to indicate a problem with the JVM.
  • OutOfMemoryError. Thrown when there is no more memory available to allocate an object or perform garbage collection.
  • NoClassDefFoundError. Thrown when the JVM cannot find a class definition that was found at compile time.
  • StackOverflowError. Thrown to indicate that a stack overflow occurs.
Unchecked exceptions are also known as runtime exceptions and are subclasses of java.lang.RuntimeException. All other subclasses of java.lang.Exception are checked exceptions.

Difference between Checked and Unchecked exception

Checked exception Unchecked exception
Checked exception is required to be handled by compile time using try-catch block or else method should use throws keyword. Unchecked exceptions are not required to be handled in the program or to mention them in throws clause.
Super class of all checked exceptions is Exception. Super class of all unchecked exceptions RuntimeException.
Checked exception represent scenario with higher failure rate. For example, FileNotFoundException in reading a file that is not present. Unchecked exceptions are mostly caused by poor programming. For example, NullPointerException when invoking a method on an object reference without making sure that it’s not null.