Core Module
12 min forge

Java Exception Handling

Checked vs Unchecked exceptions, try-catch-finally, and custom exceptions.

Java Exception Handling

πŸ“˜ What is it

Exception handling is a mechanism to handle runtime errors so that the normal flow of the application can be maintained. Java uses a robust hierarchy of Throwable classes.

πŸ—οΈ Hierarchy

  • Throwable: Root class.
    • Error: Irrecoverable conditions (e.g., OutOfMemoryError).
    • Exception: Recoverable conditions.
      • Checked Exceptions: Checked at compile-time (e.g., IOException).
      • Unchecked Exceptions (Runtime): Checked at runtime (e.g., NullPointerException).

⚑ Keywords

  • try: Block where code that might throw an exception is placed.
  • catch: Block that handles the exception.
  • finally: Block that executes regardless of whether an exception was thrown (used for cleanup).
  • throw: Used to explicitly throw an exception.
  • throws: Declares that a method might throw an exception.

πŸ’» Code example

java Standard
public class ExceptionExample { public static void main(String[] args) { try { int result = 10 / 0; } catch (ArithmeticException e) { System.err.println("Cannot divide by zero!"); } finally { System.out.println("Cleanup successful."); } } }

❌ Common mistakes

  • Catching Throwable: Catching Throwable or Exception indiscriminately (swallowing errors).
  • Ignoring finally: Not using finally (or try-with-resources) to close resources like file streams or database connections.
  • Checked vs Unchecked: Not understanding when to use checked exceptions (for recoverable conditions outside the app's control) vs unchecked (for programming errors).