9.1 try, catch, and finally
Real-world software encounters runtime anomalies: network dropouts, missing files, arithmetic division by zero, or null pointer dereferences. Java's exception handling mechanism intercepts these failures cleanly, preventing application crashes.
The try-catch-finally Architecture
try: Encloses risky code that might throw an exception.catch: Catches and handles specific exception types, restoring orderly flow.finally: Executes unconditionally whether an exception was thrown, caught, or not thrown at all. Standard location for resource cleanup (closing sockets, DB connections, streams).
try {
int result = 10 / 0; // throws ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero: " + e.getMessage());
} finally {
System.out.println("Cleanup runs regardless");
}
💡 Placement & Interview Deep-Dive
- The Finally Return Trap: If a method has a
returnstatement inside thetryorcatchblock, and also has areturninside thefinallyblock, the return in finally overrides everything!public static int test() { try { return 10; } finally { return 20; } // Returns 20! } - When does a finally block NOT execute? There are only two scenarios:
- If
System.exit(0)is invoked, which terminates the JVM process immediately. - In catastrophic hardware failures (e.g. power cutoff, OS kill -9, or host machine crash).
- If
9.2 Checked vs Unchecked Exceptions
Every throwable event in Java descends from the root java.lang.Throwable class, which splits into two fundamental branches: Exception and Error.
Checked vs Unchecked Exception Split
- Checked Exceptions: Exceptions that inherit directly from
Exception(excludingRuntimeException). Verified by the compiler at compile-time: the programmer must either catch them or declare them in the method signature usingthrows(e.g.IOException,SQLException). - Unchecked Exceptions (Runtime Exceptions): Exceptions that inherit from
RuntimeException. Not checked by the compiler. Represent programming logic flaws (e.g.NullPointerException,ArrayIndexOutOfBoundsException). - Errors: Severe system-level failures that applications are not expected to catch or handle (e.g.
OutOfMemoryError,StackOverflowError).
9.3 throw, throws, and Custom Exceptions
Java distinguishes between actively raising an exception and declaring potential exceptions:
throw: An executable action statement inside a method body used to instantiate and throw a specific exception:if (amount > balance) { throw new InsufficientFundsException("Balance too low: " + amount); }throws: A clause in a method signature warning callers that the method may propagate checked exceptions:public void readFile(String path) throws IOException { ... }
throw actually raises one specific exception, right where you write it. throws is only a signature-level warning label, telling callers 'this method might send a checked exception your way.'
Creating Custom Exceptions
Extend Exception to create a checked exception; extend RuntimeException to create an unchecked exception:
public class InsufficientFundsException extends Exception {
public InsufficientFundsException(String message) {
super(message);
}
}