Using Try-Catch in Java

To handle exceptions in Java, use the try-catch statement. The try block contains code that may throw an exception, and the catch block contains code that runs if an exception occurs. An exception that is not caught stops the program. A try block can be followed by multiple catch blocks, one for each exception type. The optional finally block runs after try and catch whether or not an exception was thrown. In this Java Try-Catch Example, we catch the ArithmeticException thrown when dividing by zero. Click Execute to run the Java Try-Catch Example online and see the result.
Using Try-Catch in Java Execute
public class TryCatchExample {

    public static void main(String[] args) {
        int[] numbers = {10, 5, 0};

        try {
            int result = numbers[1] / numbers[2];
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Error: Division by zero is not allowed!");
            System.out.println("Message: " + e.getMessage());
        } finally {
            System.out.println("This code will run regardless of an exception.");
        }
    }
}

Java try-catch Syntax

The try-catch statement consists of a try block, one or more catch blocks and an optional finally block. Each catch block specifies the type of exception it handles.

Java try-catch-finally Syntax
try {
    // code that can throw an exception
} catch (ExceptionType1 e) {
    // code that handles ExceptionType1
} catch (ExceptionType2 e) {
    // code that handles ExceptionType2
} finally {
    // code that runs in both cases
}

How does try-catch work in Java?

If the try block finishes without an exception, Java skips all catch blocks. If an exception is thrown, Java checks the catch blocks from top to bottom. A catch block matches when it names the exception class or one of its superclasses. If no catch block matches, the exception passes to the method that called this one. The finally block runs at the end in every case, even when no catch block matches.

Java Try-Catch Examples

The following are examples of exception handling with try-catch in Java. You can run any of these examples in the online Java code runner to see which lines are printed and which are skipped.

Catch an exception with try-catch

Reading index 5 of a two-element array throws an exception. The line after it in the try block never runs, but the program goes on after the catch block.

Java Try-Catch Example
public class TryCatchExample {
    public static void main(String[] args) {
        String[] items = {"apple", "banana"};
        try {
            System.out.println(items[0]);
            System.out.println(items[5]);
            System.out.println("This line is skipped");
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Caught: " + e.getMessage());
        }
        System.out.println("The program continues");
    }
}

// output:
// apple
// Caught: Index 5 out of bounds for length 2
// The program continues

Run code in a finally block

The finally block runs whether the try block ends normally or with an exception. It runs even when try or catch returns a value.

Java Try-Catch-Finally Example
public class FinallyExample {
    public static void main(String[] args) {
        System.out.println(divide(10, 2));
        System.out.println(divide(10, 0));
    }

    static String divide(int a, int b) {
        try {
            return "Result: " + (a / b);
        } catch (ArithmeticException e) {
            return "Error: " + e.getMessage();
        } finally {
            System.out.println("Dividing " + a + " by " + b);
        }
    }
}

// output:
// Dividing 10 by 2
// Result: 5
// Dividing 10 by 0
// Error: / by zero

Catch multiple exceptions

A try block can have several catch blocks, and Java runs the first one that matches. A catch block for a subclass must come before a catch block for its superclass. To handle unrelated exception types the same way, list them in one catch block separated by |.

Java Multiple Catch Blocks Example
public class MultiCatchExample {
    public static void main(String[] args) {
        String[] inputs = {"4", "abc", "0"};
        for (String input : inputs) {
            try {
                System.out.println(100 / Integer.parseInt(input));
            } catch (NumberFormatException e) {
                System.out.println("Not a number: " + input);
            } catch (ArithmeticException e) {
                System.out.println("Cannot divide by zero");
            }
        }
    }
}

// output:
// 25
// Not a number: abc
// Cannot divide by zero

Throw an exception and catch it in the caller

The throw statement throws an exception object. A method that does not catch it passes it up, and the calling method handles it in its own try-catch block.

Java Throw and Catch Example
public class ThrowExample {
    static int checkAge(int age) {
        if (age < 0) {
            throw new IllegalArgumentException("Age cannot be negative: " + age);
        }
        return age;
    }

    public static void main(String[] args) {
        try {
            System.out.println(checkAge(30));
            System.out.println(checkAge(-1));
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }
    }
}

// output:
// 30
// Age cannot be negative: -1

See also

Updated: