Lesson 14: Exception Handling: try/catch/finally
15 Jul 2026 1 min Swarnil Singhai
Exceptions separate error-handling code from the main logic, and finally guarantees cleanup runs whether or not an error occurred.
Real-time example
A file-upload service must always close the input stream, even if parsing the file throws — that's what finally is for.
try {
InputStream in = new FileInputStream("upload.csv");
parseCsv(in);
} catch (IOException e) {
System.out.println("Upload failed: " + e.getMessage());
} finally {
System.out.println("Cleanup: closing resources");
}
What's happening
finally runs on the success path, the exception path, and even if you return early inside try — it's the one guaranteed block.
Prefer try-with-resources over manual finally-close for anything implementing AutoCloseable.
Advertisement