Java throws 关键字
定义和用法
throws 关键字指示方法可能抛出什么异常类型。
Java 中有很多可用的异常类型,例如:
- ArithmeticException
- ClassNotFoundException
- ArrayIndexOutOfBoundsException
- SecurityException
throw 与 throws 的区别:
| throw | throws |
|---|---|
| 用于抛出方法的异常 | 用于指示方法可能抛出什么异常类型 |
| 不能抛出多个异常 | 可以声明多个异常 |
语法:
|
语法:
|
相关页面
实例
如果年龄小于 18 岁,则抛出异常(打印“拒绝访问”)。如果年龄为 18 岁或以上,请打印“允许访问”:
public class Main {
static void checkAge(int age) throws ArithmeticException {
if (age < 18) {
throw new ArithmeticException("拒绝访问 - 您必须至少满 18 岁。");
}
else {
System.out.println("允许访问 - 您的年龄足够大!");
}
}
public static void main(String[] args) {
checkAge(15); // 将年龄设置为 15(小于 18)
}
}