Exception Handling
Prerequisites: Enums
Java splits exceptions into two kinds. Checked exceptions (like
IOException) must be either caught or declared with throws — the
compiler enforces this. Unchecked exceptions (RuntimeException
and its subclasses, like NullPointerException) need no such
declaration, and usually signal a programming mistake rather than an
expected, recoverable condition.
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Can't divide by zero: " + e.getMessage());
} finally {
System.out.println("This always runs");
}
Can't divide by zero: / by zero
This always runs
try-with-resources automatically closes a resource (like a file)
even if an exception is thrown, without a manual finally:
try (var reader = new java.io.FileReader("data.txt")) {
// use reader
} catch (java.io.IOException e) {
System.out.println("Couldn't read file: " + e.getMessage());
}
Common mistakes
- Catching
Exception(or worse,Throwable) generically "to be safe" — this also silently swallows bugs that should have crashed loudly during development. Catch the specific exception type you actually expect and know how to handle. - An empty
catchblock that discards the error entirely, making a real failure invisible.
Practice
Write code that attempts to parse "abc" as an integer with
Integer.parseInt, catching NumberFormatException and printing a
friendly message.
Show solution
try {
int n = Integer.parseInt("abc");
} catch (NumberFormatException e) {
System.out.println("That wasn't a valid number");
}