What is the Difference Between Checked Exception and Runtime Exception?

🆚 Go to Comparative Table 🆚

The main difference between a checked exception and a runtime (or unchecked) exception in Java lies in how they are caught and handled due to their compile-time checking behavior. Here are the key differences:

  1. Checked Exceptions:
  • Caught at compile time.
  • Must be handled either by re-throwing or with a try-catch block.
  • Represent errors outside the control of the program, such as IOException, SQLException, and ParseException.
  • Typically used for recoverable conditions.
  1. Runtime Exceptions (Unchecked Exceptions):
  • Occur at runtime.
  • Are not required to be caught or declared in a throws clause.
  • Represent programming errors and are typically fatal, such as NullPointerException, ArrayIndexOutOfBoundsException, and ArithmeticException.
  • Subclasses of the RuntimeException class, as well as the Error class and its subclasses.

In summary, checked exceptions are caught at compile time and must be handled, while runtime exceptions occur at runtime and are not required to be handled. Checked exceptions are typically used for recoverable conditions, while runtime exceptions represent programming errors that are often fatal.

Comparative Table: Checked Exception vs Runtime Exception

The main difference between checked and runtime (unchecked) exceptions lies in how they are handled during the development process and at runtime. Here is a comparison table highlighting the key differences between checked and runtime exceptions:

Checked Exception Runtime Exception
Occur at compile-time Occur at runtime
Mandatory to handle in code using try-catch or try-finally blocks Optional to handle in code
Must declare the exception using the throws keyword in the method definition No need to declare the exception
Enforces proper handling of error conditions Less strict, does not require handling
Derived from the Exception class (e.g., IOException, ClassNotFoundException) Derived from the RuntimeException class (e.g., NullPointerException, ArrayIndexOutOfBoundsException)
Can make code uglier when needing to handle multiple exceptions Cleaner code as they are usually caught by a generic "catch every runtime exception" block

In summary, checked exceptions are caught at compile-time and require mandatory handling in the code, while runtime exceptions are caught at runtime and their handling is optional. Checked exceptions typically derive from the Exception class, whereas runtime exceptions derive from the RuntimeException class.