An exception is an unexpected event that occurs during program execution and disrupts normal flow.
Java handles exceptions using try-catch mechanism, allowing your app to fail gracefully.

Exception Hierarchy (Simplified)

Throwable
 β”œβ”€β”€ Error (not recoverable)
 └── Exception
      β”œβ”€β”€ Checked Exceptions (must be handled)
      └── Unchecked Exceptions (RuntimeException)

Basic try-catch Example

try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("Can't divide by zero!");
}

Keywords

KeywordPurpose
tryWraps risky code
catchHandles specific exception types
finallyReturns no matter what (cleanup code)
throwManually throw an exception
throwsDeclare exceptions a method might throw

Try-Catch-Finally

try {
    int[] nums = {1, 2};
    System.out.println(nums[5]);
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("Index error!");
} finally {
    System.out.println("Cleanup code runs here.");
}

Throw & Throws

void checkAge(int age) throws IllegalArgumentException {
    if (age < 18) {
        throw new IllegalArgumentException("Too young");
    }
}

Checked vs Unchecked Exceptions

TypeHandled at Compile Time?Example
CheckedYesIOException, SQLException
UncheckedNoNullPointerException, ArithmeticException

Tip

Be ready to explain:

  • wy unchecked exceptions aren’t forced to be caught,
  • difference between throw and throws,
  • use of finally for resource cleanup,
  • custom exceptions (class MyException extends Exception).

Parent: _Exceptions