Java.Core.What is the difference between checked and unchecked exceptions?

Here’s a clear breakdown of the difference between checked and unchecked exceptions in Java:


✅ Checked Exceptions

Definition

These are exceptions that the compiler forces you to handle — either by using a try-catch block or by declaring them in the method signature using throws.

Examples

  • IOException
  • SQLException
  • FileNotFoundException

Key Features

  • Checked at compile time.
  • The compiler checks that your code either handles these exceptions (with try-catch) or explicitly declares them (with throws).
  • Typically used for recoverable situations — things you can anticipate and handle gracefully, like file not found, database issues, etc.

❌ Unchecked Exceptions

Definition

These are exceptions that the compiler does not force you to handle. They usually indicate programming bugs (logic errors) rather than recoverable conditions.

Examples

  • NullPointerException
  • ArrayIndexOutOfBoundsException
  • IllegalArgumentException

Key Features

  • Checked at runtime.
  • No need to catch or declare them.
  • Usually caused by flaws in code logic — like accessing a null reference or an out-of-bounds index.

Quick Summary Table

Checked ExceptionUnchecked Exception
Checked by Compiler?✅ Yes❌ No
Declared in method signature?✅ Required❌ Not required
TypeRecoverableProgramming bug
ExamplesIOException, SQLExceptionNullPointerException, ArrayIndexOutOfBoundsException

A Rule of Thumb

  • Checked Exceptions = External problems (files, network, DB)
  • Unchecked Exceptions = Internal problems (bugs, logic errors)
This entry was posted in Без рубрики. Bookmark the permalink.