Java Exception Handling Guide
Ad
Exceptions in Java
Exceptions signal errors during execution. Java uses try/catch/finally and distinguishes checked vs unchecked exceptions.
try/catch/finally
try {
int[] arr = new int[3];
arr[5] = 10; // throws
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Bad index: " + e.getMessage());
} finally {
System.out.println("Always runs");
}
Checked vs Unchecked
| Type | Must handle? | Example |
|---|---|---|
| Checked | Yes (compile) | IOException |
| Unchecked | No | NullPointerException |
Throwing Exceptions
public void setAge(int age) {
if (age < 0) throw new IllegalArgumentException("Age < 0");
}
try-with-resources
try (BufferedReader r = new BufferedReader(new FileReader("f.txt"))) {
return r.readLine();
} // file auto-closed
FAQs
Should I catch Exception broadly?
No — catch specific types. Broad catches hide bugs. More in our Java section.
What is the finally block for?
Cleanup that must run whether or not an exception occurred.
