Java throw 关键字
示例
如果 age 小于 18,则抛出异常(打印 "Access denied")。如果 age 为 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 等。
异常类型通常与自定义**方法**一起使用,如上例所示。
throw 和 throws 之间的区别
| throw | throws |
|---|---|
| 用于为方法抛出异常 | 用于指示方法可能抛出的异常类型 |
| 不能抛出多个异常 | 可以声明多个异常 |
语法
|
语法
|
相关页面
在我们的 Java Try..Catch 教程 中了解更多关于异常的信息。