0

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

Nor.Z
  • 555
  • 1
  • 5
  • 13
  • 3
    read about checked and unchecked exceptions – Eran Jan 03 '21 at 05:34
  • As Eran says ^^^. Note that `ArithmeticException` is an uncheck exception. – Stephen C Jan 03 '21 at 05:36
  • Voted to close as duplicate of [Understanding checked vs unchecked exceptions in Java](https://stackoverflow.com/questions/6115896/understanding-checked-vs-unchecked-exceptions-in-java) – Max Vollmer Jan 03 '21 at 05:37

0 Answers0