Java Reference ยท Keywords and Statements
The try, catch and finally statements
Reference for Java try, catch and finally: handling exceptions, multi-catch, catch order, finally guarantees, rethrowing, suppressed exceptions and pitfalls.
A try block contains code that might throw an exception. One or more catch blocks handle specific exception types, and an optional finally block runs afterwards whether or not an exception occurred. You need at least one catch or a finally (or a resource list, see try-with-resources).
When an exception is thrown, the JVM looks for the first catch whose parameter type matches (the exception is an instance of that type) and jumps there. If none matches, the exception propagates to the caller, after finally has run.
try { risky(); } catch (IOException | IllegalStateException e) { handle(e); } finally { cleanup(); }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
try { ... } catch (ExceptionType1 | ExceptionType2 name) { ... } catch (OtherType name) { ... } finally { ... }
| Part | Description |
|---|---|
catch parameter |
Must be Throwable or a subclass. In a multi-catch the types must not be subclasses of each other; the parameter is implicitly final. |
finally |
Runs after the try and catch blocks, however they ended: normally, by return, break, continue or by an exception. |
Usage notes
- Order matters. Catch blocks are tried top to bottom; a catch for a superclass before its subclass is a compile error ("already been caught").
- Checked exceptions: catching a checked exception type that the
trybody cannot throw is a compile error (exceptExceptionandThrowable). finallydoes not run only if the JVM stops (System.exit(), crash) or the thread is killed. Areturnorthrowinsidefinallyreplaces the pending result or exception and hides bugs.- Do not swallow exceptions. An empty
catchblock hides failures; log or rethrow, and keep the original as the cause:new XException("...", e). - Catch narrowly. Catching
ExceptionorThrowablealso catches bugs and, forThrowable,OutOfMemoryErrorand other errors that you usually cannot handle. - Cost: creating an exception captures a stack trace, which is slow compared with a normal return. Do not use exceptions for ordinary control flow.
- Scope: variables declared in
tryare not visible incatchorfinally. Declare them before thetry. - Precise rethrow:
catch (Exception e) { throw e; }rethrows only the checked types the body can actually throw (Java 7+), ifeis not reassigned. InterruptedException: if you catch it and cannot propagate it, restore the flag withThread.currentThread().interrupt().- Resources that must be closed are better handled by try-with-resources than by manual
finallycode.