Handle errors gracefully — checked vs unchecked, try-with-resources, custom exceptions.
Published January 22, 2025
Checked exceptions (subclasses of Exception, not RuntimeException) must be caught or declared:
public String readFile(String path) throws IOException {
return Files.readString(Path.of(path)); // checked — must declare or catch
}
Unchecked exceptions (subclasses of RuntimeException) don't need to be declared:
public int divide(int a, int b) {
return a / b; // ArithmeticException if b == 0 — unchecked
}
Automatically closes AutoCloseable resources:
try (InputStream in = new FileInputStream("input.txt");
OutputStream out = new FileOutputStream("output.txt")) {
// use in and out
} // both closed automatically, even if an exception is thrown
// Unchecked custom exception (recommended for most cases)
public class OrderNotFoundException extends RuntimeException {
private final String orderId;
public OrderNotFoundException(String orderId) {
super("Order not found: " + orderId);
this.orderId = orderId;
}
public String getOrderId() { return orderId; }
}
Exception or Throwable// ❌ Don't do this
try { ... } catch (Exception e) { } // silent swallow
// ✅ Do this
try { ... } catch (IOException e) {
log.error("Failed to read file: {}", path, e);
throw new FileProcessingException("Failed to process " + path, e);
}
Interviewers often ask: "When would you use a checked exception vs an unchecked exception?"
Use checked when the caller can reasonably recover (file not found → prompt user for a different path). Use unchecked for programmer errors (null pointer, illegal argument) where recovery is not expected.