To Catch or not to Catch?–An Exceptional Question

Java makes exception handling a piece of cake compared to the exception handling mechanisms in languages like C++. Exceptions in Java are mostly managed by the runtime environment and do not burden the programmer.

Java provides two ways to define and detect exceptional conditions in a Java program: runtime exceptions (objects of the Exception class) and errors (objects of the Error class). Both these classes inherit from the Throwable class. Classes that are subclasses of the Error class should never be caught or extended. Although Java enables you to extend the Error class, you should not use this feature carelessly. Error and subclasses of Error are thrown by the JVM and should not be managed by the developers.

The Throwable class is also subclassed by the Exception class. The Exception class has two further subcategories: RuntimeException and other exceptions (subclassed directly from Exception). Runtime exceptions also should not be caught nor extended by user programs. They are meant to be propagated to the top level of the call stack and should be managed by the runtime system.

If you want to catch exceptions in your code, you should subclass them directly from the Exception class (and not the RuntimeException class). Here’s the hierarchy for the exception classes in Java:

  class Throwable extends Object  // Never subclass or catch these !! class Error extends Throwable  class Exception extends Throwable  // Never subclass or catch these class RuntimeException extends Exception  // Creating user exceptions class MyException extends Exception 
Share the Post:
Share on facebook
Share on twitter
Share on linkedin


Recent Articles: