try, catch, finally and try-with-resources
try, catch, and finally describe what Java should do when an operation may fail. The important idea is not the keywords themselves, but the control-flow decision: keep the normal result, recover from a known failure, or clean up a resource before leaving the method.
Basic control flow
Code inside try runs first. If it completes, Java skips the catch blocks and then executes finally. If an exception is thrown, Java searches the catch blocks from top to bottom. A matching block handles the exception, and finally still runs afterward. If no block matches, finally runs and the exception continues to the caller.
static int parseAge(String text) {
try {
return Integer.parseInt(text);
} catch (NumberFormatException ex) {
return 0; // the chosen fallback for this example
} finally {
System.out.println("parse attempt finished");
}
}
Catch the most specific type that you can handle. In a multi-catch, types must be unrelated siblings: catch (IOException | SecurityException ex). The variable has a common static type, so use multi-catch only when the response is genuinely the same. Put catch (IOException) before catch (Exception); otherwise the broad block makes the specific one unreachable.
finally and return
finally is intended for cleanup, not for changing a method result. It runs even when try or catch returns, but a return inside finally overrides the earlier return and hides an exception. This is why production code should never return from finally.
static int example() {
try {
return 1;
} finally {
// return 2; // do not do this
System.out.println("cleanup");
}
}
Resources and try-with-resources
A resource is an object that must be closed, such as InputStream, Reader, or a JDBC statement. try-with-resources closes every declared AutoCloseable resource automatically, including when reading throws. Resources close in reverse declaration order. If both the body and close() fail, Java keeps the body exception and attaches the close failure as a suppressed exception.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
static String readConfig(Path path) throws IOException {
try (var reader = Files.newBufferedReader(path)) {
return reader.readLine();
}
}
| Situation | Result |
|---|---|
try succeeds |
catch is skipped; finally runs |
| matching exception | matching catch runs; finally runs |
no matching catch |
finally runs; exception propagates |
| resource in try-with-resources | resource closes automatically |
| failure during close | close failure becomes suppressed when another failure exists |
Do not use an empty catch block. If the current layer cannot recover, add context and rethrow or let a higher layer handle the exception. Never close the same resource manually inside try-with-resources unless the API explicitly requires it.
Glossary
- bytecode
- Platform-independent compiled code that the JVM can execute.
- class
- A blueprint that defines fields and methods for objects in object-oriented programming.
- object
- A runtime instance of a class with its own state and behavior.
- method
- A named block of behavior that belongs to a class or object and can be called by code.
- field
- A variable stored inside a class or object that represents part of its state.
- constructor
- A special method-like block used to create and initialize a new object.
- package
- A namespace that groups related Java classes and helps organize code.
- interface
- A contract that defines methods a class can implement without prescribing all internal details.
- generics
- A language feature that lets code work with types as parameters while preserving type safety.
- type erasure
- The Java compiler process that removes most generic type details from runtime bytecode.
- collection
- A data structure that stores a group of elements and provides operations over them.
- list
- An ordered collection where elements have positions and duplicates are allowed.
- set
- A collection that stores unique elements and is commonly used for membership checks.
- map
- A key-value data structure where each key points to a value.
- queue
- A collection designed for processing elements in a defined order, often first-in-first-out.
- lambda
- A compact function-like expression used to pass behavior as data.
- functional interface
- An interface with one abstract method, suitable for lambdas and method references.
- stream
- A Java API for processing data sequences with operations such as map, filter, and reduce.
- optional
- A container object that represents a value that may or may not be present.
- thread
- An independent path of execution inside a running program.
- synchronization
- Coordination that protects shared data when multiple threads access it.
- heap
- The runtime memory area where Java objects are allocated.
- stack
- The runtime memory area that stores method calls, local variables, and call frames.
- garbage collector
- A JVM component that automatically frees memory occupied by objects no longer reachable.
- memory leak
- A situation where memory remains occupied because objects are still referenced but no longer useful.