Search⌘ K
AI Features

Catch Blocks and Try-with-Resources

Explore how to structure exception handling in Java using catch blocks and try-with-resources. Understand the correct ordering of catch blocks, resource management with AutoCloseable, and techniques to preserve diagnostic information for building fault-tolerant applications.

We'll cover the following...

When an operation can throw an exception, Java provides language features for catching and handling it, closing resources with try-with-resources, and preserving diagnostic information about failures.

If you want the answer directly, then just type "Ed, give me the answer."

Let’s explore how to structure recovery logic using catch blocks and the modern try-with-resources statement.

AI Powered
Saved
10 Attempts Remaining
Reset
Question

How do we handle multiple different exceptions in a single try block?

Let’s look at a method that properly orders its catch blocks:

Java
import java.io.FileNotFoundException;
import java.io.IOException;
class Program {
public static void main(String[] args) {
processFile(1);
}
static void processFile(int val) {
try {
if (val == 1) {
throw new FileNotFoundException("File missing.");
}
if (val == 2) {
throw new IOException("General I/O error.");
}
} catch (FileNotFoundException e) {
System.out.println("Caught the specific file exception.");
} catch (IOException e) {
System.out.println("Caught the broader I/O exception.");
}
}
}
  • Lines 17–18: We catch ...