What is the Difference Between Checked and Unchecked Exception in Java?

🆚 Go to Comparative Table 🆚

In Java, there are two types of exceptions: checked and unchecked exceptions. The main differences between them are:

  1. Checked exceptions:
  • Occur at compile time when the source code is transformed into executable code.
  • Are checked by the compiler.
  • Can be created manually.
  • Are counted as subclasses of the class.
  • Require the Java Virtual Machine to catch or handle the exception.
  • Examples include IOException, SQLException, and ParseException.
  1. Unchecked exceptions:
  • Occur at runtime when the executable program starts running.
  • Are not checked by the compiler.
  • Can also be created manually.
  • Happen at runtime and are not included in the exception class.
  • Do not require the Java Virtual Machine to catch or handle the exception.
  • Examples include NullPointerException, ArithmeticException, and ArrayIndexOutOfBoundsException.

In summary, checked exceptions are caught at compile time and must be handled or declared in a throws clause, while unchecked exceptions are caught at runtime and do not require handling or specification in a throws clause.

Comparative Table: Checked vs Unchecked Exception in Java

Here is a table comparing the differences between checked and unchecked exceptions in Java:

Feature Checked Exception Unchecked Exception
Time of occurrence Compile time Runtime
Compiler check Yes No
Handling Must be handled either by re-throwing or with a try-catch block Not required to be handled
Subclass of Exception class Yes No, they are runtime exceptions
Examples IOException, SQLException, ParseException NullPointerException, ArithmeticException, ArrayIndexOutOfBoundsException

Checked exceptions are caught at compile time and must be handled either by re-throwing or with a try-catch block. They are subclasses of the Exception class, and examples include IOException, SQLException, and ParseException.

Unchecked exceptions, also known as runtime exceptions, occur at runtime and are not checked by the compiler. They are not required to be handled at compile time, as they are generated by mistakes in the program. Examples of unchecked exceptions include NullPointerException, ArithmeticException, and ArrayIndexOutOfBoundsException.