ArithmeticException
is an unchecked exception, since it extends RuntimeException
. Exception
, by contrast, is an checked exception type, as it does not extend either RuntimeException
or Error
.
Checked exceptions must be declared in the throws clause of the method signature of any method that can throw them. Unchecked exceptions do not.
Using your example, adding throws Exception
will be enough to get the method to compile. Note though that any calling code would then need to handle the exception, either by catching it or declaring it as being thrown.
public static void divide(double x, double y) throws Exception {
if (y == 0){
throw new Exception("Cannot divide by zero.");
// Generates error message that states the exception type is unhanded
}
else
System.out.println(x + " divided by " + y + " is " + x/y);
// other code follows
}
This is documented in the Java Language Specification (JLS):
11.1.1. The Kinds of Exceptions
[…]
The unchecked exception classes are the run-time exception classes and the error classes.
The checked exception classes are all exception classes other than the unchecked exception classes. That is, the checked exception classes are Throwable
and all its subclasses other than RuntimeException
and its subclasses and Error
and its subclasses.
[…]
11.2. Compile-Time Checking of Exceptions
The Java programming language requires that a program contains handlers for checked exceptions which can result from execution of a method or constructor (§8.4.6, §8.8.5). This compile-time checking for the presence of exception handlers is designed to reduce the number of exceptions which are not properly handled. For each checked exception which is a possible result, the throws
clause for the method or constructor must mention the class of that exception or one of the superclasses of the class of that exception (§11.2.3).
[…]
The unchecked exception classes (§11.1.1) are exempted from compile-time checking.