๐Ÿ“Š We use cookies & analytics to improve your experience. Learn more
Latest

Java Programming Foundations Module 3 ยท Lesson 7 of 15

0% Exit to course

Module 3 ยท Exceptions, files and the interview set Lesson 7 of 15

Exceptions and try-with-resources

Learning objective

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.

Java
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.

Create free account or sign in

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.

Next recommended course Python for Absolute Beginners