Module 3 ยท Exceptions, files and the interview set Lesson 7 of 15
Exceptions and try-with-resources
Checked exceptions must be handled or declared, unchecked ones are usually bugs. Neither should ever be swallowed with an empty catch block โ that is how a system fails silently.
The concept
An exception is a failure travelling up the call stack until somebody handles it. try { โฆ } catch (IOException e) { โฆ } finally { โฆ } is the shape: the risk in the try, the handling in the catch, the clean-up in finally โ and throw new IllegalArgumentException("age must be positive") is how your own code reports a bad input rather than returning a wrong number.
Checked exceptions must be declared or caught, which is why file work in Java looks noisy: throws IOException on the method, or a catch around it. try-with-resources โ try (BufferedReader r = Files.newBufferedReader(path)) { โฆ } โ closes the file for you even when it throws, which is the modern replacement for a finally block.
try {
int n = Integer.parseInt("abc");
} catch (NumberFormatException e) {
System.out.println("Not a number: " + e.getMessage());
} finally {
// runs whether or not an exception was thrown
}
// try-with-resources closes the reader for you, even on error.
try (BufferedReader r = new BufferedReader(new FileReader("data.txt"))) {
String line;
while ((line = r.readLine()) != null) System.out.println(line);
} catch (IOException e) {
System.out.println("Could not read: " + e.getMessage());
}Common mistakes
The mistakes are an empty catch block that swallows the error silently, which turns a bug into mysterious missing data, and catching Exception everywhere so nothing is ever reported precisely. Catch the narrowest type you can, and always do something with it: log it or tell the user.
Worked example
try (BufferedReader r = new BufferedReader(new FileReader(path))) closes the file even when the read throws. Using plain FileReader without try-with-resources leaks a file handle every time.
Your practice task
Read a file, handle a missing filename and a malformed line separately, and print a different message for each. Never leave a catch block empty.
Do this before moving on. Reading a solution teaches the shape of it; typing it teaches you.
Key takeaway
An exception is a failure travelling up the call stack until somebody handles it.
Keep your place in this course
A free account saves which lessons you have finished and unlocks the certificate. The lesson itself stays free to read.
Create free account or sign inCourse complete
You finished every lesson.
Your certificate is ready, and the projects you built are the proof to attach to an application.
Almost there
15 lessons left of 15
Finish every lesson to unlock the certificate. Each one ends in a practice task โ do them and the final project brief writes itself.