为什么我不需要在方法[java]中声明一个异常呢?

ie3xauqp  于 2021-06-29  发布在  Java
关注(0)|答案(0)|浏览(385)

这个问题在这里已经有答案了

未检查异常和运行时异常之间的差异(8个答案)
了解java中检查的和未检查的异常(21个答案)
六天前关门了。
在以下代码中:

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
我不应该把球加到 static void checkAge(int age) throws ArithmeticException{ ?
另外,如果我改变 ArithmeticExceptionException ,那我就得用 throw . 为什么?

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

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题