Multi-Catch & try-with-resources in Java
Multi-catch, catch (IOException | SQLException e), lets one catch block handle several unrelated exception types identically, avoiding duplicated handling code when two different exceptions genuinely deserve the exact same response. The caught variable's type is effectively the closest common supertype of all the listed exceptions, so only methods available on all of them can be called on it.
try-with-resources, try (Resource r = new Resource()) { ... }, automatically closes any resource declared in its parentheses once the block ends, whether it exited normally or via an exception — the resource just needs to implement the AutoCloseable interface. Before it existed, safely closing a resource required a manual finally block calling close() explicitly, which was easy to get subtly wrong, since an exception thrown from within that finally block's own close() call could mask the original exception that caused the problem in the first place.
Multi-catch syntax
catch (IOException | SQLException e) handles either listed exception type with one shared block of code.
What the caught variable's type becomes
Effectively the closest common supertype of every listed exception, limiting which methods can be called on it directly.
try-with-resources syntax
try (Resource r = new Resource()) { ... } declares a resource that gets closed automatically once the block ends.
Requires AutoCloseable
Any resource used this way must implement that interface, providing its own close() method.
Correct even when exceptions happen
The resource is closed whether the block finishes normally or throws, and multiple resources close in reverse declaration order.
import java.io.StringReader; public class ResourceDemo { public static void main(String[] args) throws Exception { try (StringReader reader = new StringReader("hi")) { System.out.println("First char code: " + reader.read()); } System.out.println("Reader closed automatically"); }}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Java yourself — building beats watching.