I am new at Java and am experiencing a bit of a problem with throwing exceptions. Namely, why is this incorrect
public static void divide(double x, double y) {
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
}
But this OK?
public static void divide(double x, double y) {
if (y == 0)
throw new ArithmeticException("Cannot divide by zero.");
else
System.out.println(x + " divided by " + y + " is " + x/y);
// other code follows
}
An ArithmeticException
is a RuntimeException
, so it doesn't need to be declared in a throws
clause or caught by a catch
block. But Exception
isn't a RuntimeException
.
Section 11.2 of the JLS covers this:
The unchecked exception classes (§11.1.1) are exempted from compile-time checking.
The "unchecked exception classes" include Error
s and RuntimeException
s.
Additionally, you'll want to check if y
is 0
, not if x / y
is 0
.