Java uses exceptions for error signaling. Use try/catch/finally to handle recoverable failures; uncaught exceptions terminate the thread and print a stack trace.
Basic syntax
try {
int n = Integer.parseInt("42");
} catch (NumberFormatException e) {
System.out.println("Bad number: " + e.getMessage());
} finally {
System.out.println("Always runs");
}
Throwing
if (amount < 0) {
throw new IllegalArgumentException("amount must be positive");
}
Important interview questions and answers
- Q: Exception vs Error?
A: Exceptions are recoverable application issues; Errors are serious JVM problems (OutOfMemoryError)—do not catch casually. - Q: finally without catch?
A: Valid—try/finally with try-with-resources preferred for I/O.
Self-check
- Which block always runs (usually)?
- When should you throw IllegalArgumentException?
Tip: Catch specific exceptions first—avoid empty catch (Exception e) {} blocks that swallow errors silently.
Interview prep
- Checked vs unchecked?
Checked exceptions extend
Exception(not RuntimeException) and must be caught or declared; unchecked extendRuntimeException.