目录

JAVA throw 关键字

❮ Java 关键字


示例

如果出现以下情况则抛出异常年龄低于 18(打印 "Access denied")。如果年龄为 18 岁或以上,请打印 "Access granted":

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(15); // Set age to 15 (which is below 18...)
  }
}

亲自试一试 »


定义和用法

这个throw关键字用于创建自定义错误。

这个throw语句与一个一起使用异常类型。 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 关键字