try, catch & finally in Java
A try block wraps code that might throw an exception; if one is thrown, execution immediately jumps out of the try block and into the first matching catch block, skipping any remaining try-block code entirely. A catch block declares the specific exception type it handles, and only runs if a thrown exception matches that type or one of its subclasses — multiple catch blocks can follow one try, each handling a different exception type, checked in order from top to bottom.
A finally block, if present, always runs after the try/catch finishes, whether an exception was thrown or not, and even if the try or catch block contains a return statement. Its most common job is releasing a resource, like a file or a connection, that absolutely must be cleaned up regardless of how the block ends.
try
Wraps code that might throw an exception, allowing the rest of the program to keep running if something goes wrong inside it.
Immediate jump on exception
The moment an exception is thrown, execution leaves the try block right away, skipping anything remaining in it.
catch
Declares an exception type it handles; a thrown exception matching that type, or a subclass of it, runs that catch block's code.
Multiple catch blocks
Checked in order from top to bottom, with only the first matching one actually running.
finally
Runs after try/catch finishes no matter what, exception or not, even across a return statement, making it the standard place for guaranteed cleanup.
public class TryCatchDemo { public static void main(String[] args) { try { int result = 10 / 0; System.out.println("Result: " + result); } catch (ArithmeticException e) { System.out.println("Caught: " + e.getMessage()); } finally { System.out.println("Finally block always runs"); } }}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.