Nor.Z
Nor.Z

Reputation: 1349

Why don't I need to declare an exception in a method [Java]?

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);
  }
}

https://www.w3schools.com/java/java_try_catch.asp

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

Answers (0)

Related Questions