Throw

You might have a method where you think certain things should be handled (like if you run into a floating point error and want to handle that case explicitly), but Java will not automatically throw an exception because it does not see an issue.

If you want to explicitly invoke an exception from a method (to let a different part of your program know that something went wrong), you use the throw keyword and create a new instance of the Exception subclass that represents the type of exception you are dealing with. [common subclasses]

public static void main(String[] args) {
    try {
        System.out.println(divide(7, 2));
    } catch (ArithmeticException e) {
        System.out.println("There was an arithmetic exception.");
    }
}

public static int divide(int a, int b) {
    int result = a / b;
    if (result != (double) a / (double) b) throw new ArithmeticException();
    System.out.println("Got to end of divide()");
    return a / b;
}

In the code above, if the integer division of a and b does not equal the exact value of a / b, the divide() method throws an ArithmeticException. This allows the main() method to handle the exception, instead of having to handle it in the divide**(**) method.

Checked and Unchecked Exceptions

What happens when you don’t bother with exception handling?

In the above case, just like how you encounter runtime errors if you divide by zero, neglecting to handle the ArithmeticException would not give you a compiler error, since ArithmeticException is an unchecked exception. You would simply get a runtime error if the exception actually occurred.

In Java, there are checked and unchecked exceptions.

Unchecked exceptions, like ArithmeticException and ArrayIndexOutOfBoundsException, are exceptions that are handled at runtime. Java does not require these to be directly handled using try/catch block, so if an unchecked exception occurs and is not handled, this will cause a RuntimeException because the program will stop running.

<aside> 💡 (Note: ArithmeticException and ArrayIndexOutOfBoundsException are two subclasses of the Exception class, which is why they are written as one word.)

</aside>

Checked exceptions are checked at compile time because if they are not handled directly (with try/catch) or declared to be thrown with the throws keyword, you will get a compile error. These exceptions will never result in a runtime exception (unless the programmer specifically handles them by making the program exit) because they must be dealt with in the code.