How an exception travels:
- Throwing creates an exception object and hands it to the runtime.
- The runtime searches back down the call stack for a machine handler.
- When it finds one, that handler catches the exception.
- If non is found anywhere, the program terminates.
Hierarchy:
Throwable
├── Error (unchecked; JVM-level, e.g. OutOfMemoryError, StackOverflowError: don't catch)
└── Exception (checked: IOException, SQLException, FileNotFoundException)
└── RuntimeException (unchecked: NullPointerException, ArithmeticException, IndexOutOfBounds…)
Checked vs unchecked:
- Checked exceptions are enforced at compile time. You must catch them or declare them with
throws.
- Unchecked exceptions usually mean a bug. The best fix to correct the code rather than catch them.
Catch rules:
- Order catches from the most specific to the most general.
- A
finally block always runs. the exceptions are a JVM exit or a killed thread.
- Multi-catch
catch (A | B ex)is allowed, and ex is implicitly final.
Throw vs throws:
throw new X() throws one exception object.
throws X in a method signature declares it and passes responsibility to the caller.
Custom exceptions:
- extending
Exception makes them checked. Extending RuntimeException makes them unchecked.
Useful methods:
getMessage()
getCause()
printStackTrace()
toString()