Reputation: 1349
In the following Code::
public class Main {
static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Access denied - You must be at least 18 years old.");
} else {
System.out.println("Access granted - You are old enough!");
}
}
public static void main(String[] args) {
checkAge(19);
checkAge(17);
}
}
Shouldn't I add throws to
static void checkAge(int age) throws ArithmeticException{
?
Also, if I change the ArithmeticException
to Exception
, then I have to use throw
. Why?
public class Main {
static void checkAge(int age) throws Exception {
if (age < 18) {
throw new Exception("Access denied - You must be at least 18 years old.");
} else {
System.out.println("Access granted - You are old enough!");
}
}
public static void main(String[] args) throws Exception {
checkAge(19);
checkAge(17);
}
}
Upvotes: 0
Views: 46