try / catch / finally
Catches exceptions; finally always runs, and try-with-resources closes resources for you.
Available since: Java 1.0
Syntax
try { … } catch (Type e) { … } finally { … }Examples
Catching an exception and a finally block:
void main() {
try {
int n = Integer.parseInt("12a");
IO.println(n);
} catch (NumberFormatException e) {
IO.println("Bad number: " + e.getMessage());
} finally {
IO.println("done");
}
}Output:
Bad number: For input string: "12a"
doneSeveral types in one catch:
void main() {
String[] inputs = {"5", "x", null};
for (String s : inputs) {
try {
IO.println(10 / Integer.parseInt(s.strip()));
} catch (NumberFormatException | NullPointerException e) {
IO.println(e.getClass().getSimpleName());
}
}
}Output:
2
NumberFormatException
NullPointerExceptiontry-with-resources closes the object in any case:
void main() {
try (var scanner = new Scanner("first line\nsecond line")) {
IO.println(scanner.nextLine());
}
}Output:
first lineNotes
catch branches are checked from top to bottom, so put specific types above general ones (Exception last). An empty catch hides errors — at least print the message.
Objects that implement AutoCloseable (files, streams, connections) can be declared in parentheses after try: close() is called automatically, even when an exception is thrown.
See also
- throw — Throws an exception and stops the method.
- throws — Declares which checked exceptions a method may throw.
- try-with-resources — A `try` block that closes opened resources automatically — files, connections, streams.
- Exception — The base class of exceptions a program can catch and handle.
Related recipes
In the tutorial
- try, catch and finally — Handling exceptions in Java — the try and catch blocks, several catch blocks, multi-catch, finally and throwing exceptions with throw.