πŸŽ‰ Special Offer !    Code: GET300OFF    Flat β‚Ή300 OFF on every Java Course
Grab Deal πŸš€

Checked & Unchecked Exception in Java  


Introduction

  • Definition:
    • Checked Exception:
      • Exceptions that are checked at compile-time by the compiler are known as Checked Exception.
      • If checked exceptions are not handled (using try-catch or throws), the code will not compile.
    • Unchecked Exception:
      • Exceptions that are ignored by compiler and not checked at compile-time but occur at runtime are known as Unchecked Exception.
      • Compiler does not force to handle the unchecked exceptions, but the program may crash if not handled.
  • Real-World Analogy:
    • Checked Exception:
      • For Example : A scheduled train delay notice β†’ we are informed in advance, and we must plan accordingly.
    • Unchecked Exception:
      • For Example : A sudden tire burst while driving β†’ happens unexpectedly, no prior warning.
  • Hierarchy:
    • Checked Exception:
      • Checked Exceptions are subclasses of Exception class excluding RuntimeException.
    • Unchecked Exception:
      • Unchecked Exceptions are subclasses of RuntimeException and all Error classes.
    • Checked and Unchecked Exception in Java
Below are some differences between Error and Exception:
Aspect Checked Exception Unchecked Exception
  Also Called Compile-Time Exceptions Runtime Exceptions
  Definition Checked Exceptions are those which are checked at compile-time by compiler Unchecked Exceptions are those which are ignored by compiler and checked at runtime by JVM
  Hierarchy Comes under the Exception class,
(excluding RuntimeException)
Comes under the RuntimeException class
  Examples IOException, SQLException NullPointerException, ArithmeticException
  Handling Must handled by try-catch or declared using throws keyword Optional to handle (but recommended)
  When occur External factors (eg. I/O and DB connection) Code mistakes (eg. null, index, /0)
  Impact Safe but lengthy Flexible but risky
  Analogy Train delay notice Tire burst
  Best Practice Always handle or declare checked exceptions properly Avoid mistakes in code or Check data before use