try / catch (Java)

try/catch is how Java handles errors. Code that might fail goes in the try block, and the catch block runs instead if an exception occurs, preventing a crash.

Java

You can catch specific exception types and have multiple catch blocks for different errors. An optional finally block always runs afterward, whether or not an exception happened — useful for cleanup like closing files.

Catching exceptions lets your program respond gracefully instead of stopping abruptly.

Examples

Java

public class Main {
    public static void main(String[] args) {
        try {
            int n = Integer.parseInt("abc");
        } catch (NumberFormatException e) {
            System.out.println("not a number");
        } finally {
            System.out.println("done");
        }
    }
}

Output:

not a number
done

Learn it in a lesson

See also

Back to the Dictionary