To Catch or not to Catch?–An Exceptional Question

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 

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist