Java Try Catch

The try-catch statement is how you actually handle exceptions in Java. You put risky code inside a try block, and if something goes wrong, the matching catch block runs instead of letting your program crash. Adding finally lets you run cleanup code no matter what happens.

The idea is simple: you tell Java, try to run this code, but if an exception is thrown, jump to the catch block and deal with it there. This keeps your program alive and lets you show a friendly message, retry, or log the problem instead of dumping a raw stack trace on the user.

Basic try-catch

public class Main {
  public static void main(String[] args) {
    try {
      int[] numbers = {10, 20, 30};
      System.out.println(numbers[5]);
    } catch (ArrayIndexOutOfBoundsException e) {
      System.out.println("Sorry, that index does not exist.");
    }
    System.out.println("The program keeps running.");
  }
}

// Output:
// Sorry, that index does not exist.
// The program keeps running.

This time the last line did print. Because we caught the exception, Java did not have to stop the program. The variable e inside the catch block is the exception object itself, and you can ask it for details like e.getMessage().

Catching more than one type

A single try block can be followed by several catch blocks, each handling a different kind of exception. Java checks them from top to bottom and runs the first one that matches. Always list more specific exceptions before more general ones, because a broad catch like Exception would swallow everything below it.

Multiple catch blocks

public class Main {
  public static void main(String[] args) {
    try {
      String text = null;
      System.out.println(text.length()); // NullPointerException
    } catch (ArithmeticException e) {
      System.out.println("Math problem: " + e.getMessage());
    } catch (NullPointerException e) {
      System.out.println("Something was null: " + e.getMessage());
    } catch (Exception e) {
      System.out.println("Some other problem happened.");
    }
  }
}

The finally block

Code inside a finally block always runs, whether an exception was thrown or not, and even if you return early. This makes it the right place to release resources such as closing a file or a database connection. If you find yourself always writing the same cleanup, finally guarantees it happens.

try-catch-finally together

public class Main {
  public static void main(String[] args) {
    try {
      int result = 10 / 0; // throws ArithmeticException
      System.out.println(result);
    } catch (ArithmeticException e) {
      System.out.println("You cannot divide by zero.");
    } finally {
      System.out.println("This always runs, cleanup done.");
    }
  }
}

// Output:
// You cannot divide by zero.
// This always runs, cleanup done.
BlockRuns whenCommon use
tryAlways entered firstWrap the risky code
catchOnly if a matching exception is thrownHandle the error
finallyAlways, error or notCleanup, closing resources
Note: Never leave a catch block empty just to make an error disappear. Swallowing exceptions silently hides bugs and makes problems almost impossible to track down later. At minimum, log the exception so you know it happened.
Note: When you are working with files or streams, prefer try-with-resources: writing try (var reader = new FileReader("data.txt")) automatically closes the resource for you, so you rarely need a manual finally block for cleanup.