Java throws 关键字
示例
如果 age 小于 18,则抛出异常(打印 "Access denied")。如果 age 为 18 或更大,则打印 "Access granted"
public class Main {
  static void checkAge(int age) throws ArithmeticException {
    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(15); // Set age to 15 (which is below 18...)
  }
}
定义和用法
throws 关键字表示方法可能抛出的异常类型。
Java 中有许多异常类型:ArithmeticException、ClassNotFoundException、ArrayIndexOutOfBoundsException、SecurityException 等。
throw 和 throws 的区别
| throw | throws | 
|---|---|
| 用于为方法抛出异常 | 用于指示方法可能抛出的异常类型 | 
| 不能抛出多个异常 | 可以声明多个异常 | 
| 语法 
 | 语法 
 | 
相关页面
在我们的 Java Try..Catch 教程 中了解更多关于异常的信息。
 
