Notes › Java
Exception Handling in Java
An exception is an event that breaks the normal flow of a program — dividing by zero, a missing file, a null reference. Handling it lets the program recover or fail with a clear message instead of crashing.
Hierarchy
Throwable
├── Error (serious, don't catch: OutOfMemoryError, StackOverflowError)
└── Exception
├── IOException, SQLException, ... ← checked
└── RuntimeException ← unchecked
├── NullPointerException
├── ArithmeticException
├── ArrayIndexOutOfBoundsException
├── IllegalArgumentException
└── NumberFormatException
Checked vs unchecked
| Checked | Unchecked | |
|---|---|---|
| Extends | Exception (not Runtime) |
RuntimeException |
| Checked by | the compiler | nobody — happens at run time |
| You must | catch it or declare throws |
nothing (but you can catch it) |
| Usually means | something outside your control (file, network) | a bug in the code |
| Examples | IOException, SQLException |
NullPointerException, ArithmeticException |
try / catch / finally
try {
int[] a = new int[3];
a[5] = 10; // throws
System.out.println("not printed");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Bad index: " + e.getMessage());
} catch (Exception e) { // more general catch goes LAST
System.out.println("Something else");
} finally {
System.out.println("always runs"); // cleanup
}
- Order catches from specific to general, or the code won't compile.
- Multi-catch:
catch (IOException | SQLException e). finallyruns whether or not an exception happens — even afterreturn. (OnlySystem.exit()or a JVM crash stops it.)
throw vs throws
void withdraw(double amount) throws InsufficientFundsException { // throws: declares it
if (amount > balance)
throw new InsufficientFundsException("Balance is only " + balance); // throw: raises it
balance -= amount;
}
throw |
throws |
|---|---|
| inside a method body | in the method signature |
| throws one exception object | lists exception types the method may throw |
Custom exceptions
class InsufficientFundsException extends Exception { // checked
public InsufficientFundsException(String msg) { super(msg); }
}
Extend RuntimeException instead for an unchecked one.
try-with-resources (Java 7+)
Anything that implements AutoCloseable is closed automatically, even when an exception happens.
try (BufferedReader br = new BufferedReader(new FileReader("data.txt"))) {
String line;
while ((line = br.readLine()) != null) System.out.println(line);
} catch (IOException e) {
e.printStackTrace();
} // br.close() called for you
Exception propagation
An unhandled exception moves up the call stack — method → its caller → … → main. If nobody catches it, the thread ends and the stack trace is printed.
Best practices
- Catch only what you can handle; don't swallow exceptions with an empty
catch. - Never catch
ErrororThrowablein normal code. - Throw early (validate input), catch late (where you can do something useful).
- Use meaningful messages, and chain the cause:
throw new ServiceException("Save failed", e);. - Don't use exceptions for normal control flow — they are slow.
Interview one-liners
- Error vs Exception: errors are serious JVM problems you shouldn't catch.
- Can we have try without catch? Yes — with
finallyor as try-with-resources. - final vs finally vs finalize: constant/non-overridable/non-inheritable · always-run block · deprecated GC hook.
- Overriding rule: an overriding method cannot throw new or broader checked exceptions.
- Related: JDK, JRE, JVM and Java Memory.