Exception (Java)

An exception is an error that occurs while a program is running, such as dividing by zero or accessing an invalid array index. If not handled, it stops the program and prints a stack trace.

Java

Java exceptions are objects that extend the Exception class. They come in two kinds: checked exceptions, which the compiler forces you to handle, and unchecked (runtime) exceptions like NullPointerException.

You deal with exceptions using try/catch blocks, or throw them yourself with the throw keyword.

Examples

Java

public class Main {
    public static void main(String[] args) {
        int[] nums = {1, 2, 3};
        try {
            System.out.println(nums[5]);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("index out of range");
        }
    }
}

Output:

index out of range

Learn it in a lesson

See also

Back to the Dictionary