目录

JAVA throws 关键字

❮ Java 关键字


示例

如果出现以下情况则抛出异常年龄低于 18(打印 "Access denied")。如果年龄为 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, ETC。

之间的差异throwthrows:

throw throws
Used to throw an exception for a method Used to indicate what exception type may be thrown by a method
Cannot throw multiple exceptions Can declare multiple exceptions
Syntax:
  • throw is followed by an object (new type)
  • used inside the method
Syntax:
  • throws is followed by a class
  • and used with the method signature

相关页面

详细了解我们的异常Java Try..Catch 教程


❮ Java 关键字