Lesson 2 of 8
try-catch-finally & Multi-catch
The try-catch-finally block is Java's exception handling mechanism. try wraps risky code, catch handles specific exceptions, finally always runs (for cleanup). Multi-catch (Java 7+) handles multiple exception types in one catch block cleanly.
Exception Handling Patterns
import java.io.*;
import java.util.*;
public class TryCatchDemo {
public static void main(String[] args) {
// Basic try-catch-finally
String result = null;
try {
result = riskyOperation(); // may throw
processResult(result); // may also throw
} catch (IllegalArgumentException e) {
System.err.println("Bad argument: " + e.getMessage());
} catch (IOException e) {
System.err.println("I/O error: " + e.getMessage());
} catch (RuntimeException e) { // catch broader after specific
System.err.println("Unexpected: " + e.getMessage());
} finally {
System.out.println("finally always runs - use for cleanup");
// even if exception was not caught (re-thrown), finally runs
}
// Multi-catch - Java 7+ (DRY: same handling for multiple types)
try {
String text = parseInput(args);
int num = Integer.parseInt(text);
} catch (ArrayIndexOutOfBoundsException | NumberFormatException e) {
// Both handled the same way - concise
System.err.println("Invalid input: " + e.getMessage());
}
// Re-throwing: catch, log, then rethrow to let caller handle
try {
processPayment(100.0);
} catch (Exception e) {
System.err.println("Payment failed, logging: " + e.getMessage());
throw e; // rethrow - preserves original stack trace
}
}
// finally semantics - always runs, even with return in try
public static int test() {
try {
return 1; // 'return' noted, but finally runs first
} finally {
System.out.println("finally ran!"); // always printed
// return 2; // WARNING: this overrides try's return!
}
}
static String riskyOperation() throws IOException { throw new IOException("disk error"); }
static void processResult(String s) { if (s == null) throw new IllegalArgumentException("null result"); }
static String parseInput(String[] args) { return args[0]; }
static void processPayment(double amount) { throw new RuntimeException("Gateway timeout"); }
}Quick Quiz
Tip
Tip
Practice trycatchfinally Multicatch in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for try-catch-finally & Multi-catch
Practice Task
Note
Practice Task - (1) Write a working example of trycatchfinally Multicatch from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with trycatchfinally Multicatch is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready java code.
Finished this lesson?