Introduction to Exceptions

Imagine a program functioning as a factory. Any defect disrupts the line, much like errors or exceptions, that interrupt the program. Exceptions, or events that disrupt the typical flow provide error details through representative objects in Java.

Java organizes exceptions into a hierarchy. Frequent exceptions include ArithmeticException, IllegalArgumentException, NullPointerException, and IOException. Our program must handle these to ensure smooth execution.

Throwing Exceptions

In Java, we manually throw exceptions using the throw keyword, much like throwing a ball. This practice is useful for pre-empting known errors. There are different types of exceptions, but here is a small example throwing IllegalArgumentException when the provided name is null.

public class Main {
    static void greet(String name) { 
        if (name == null) {
            // We cannot greet a person without a name
            throw new IllegalArgumentException("Name cannot be null"); // Exception thrown here
        }
        System.out.println("Hi, " + name);
    }

    public static void main(String[] args) {
        greet("John"); // Output: Hi, John
        greet(null); // throws an Exception and interrupts the program's execution
    }
}

We throw an IllegalArgumentException when name is null, interrupting the program's execution.

Catching Exceptions: try-catch Block

The try-catch block manages exceptions. In the code below, an attempt to access a nonexistent array index triggers an ArrayIndexOutOfBoundsException. Our try-catch block then catches this exception.

public class Main {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3};
        try {
            System.out.println(numbers[5]);  // Attempting to access non-existent index 5
            // ArrayIndexOutOfBoundsException is triggered, we should handle it to avoid our program to fail
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("That index does not exist in the array. Error: " + e.getMessage()); // Handling the exception
            // e.getMessage() is used to get the exception error message
        }
    }
}
Exception Propagation: What Happens If an Exception is Not Caught?
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal