如果出现以下情况则抛出异常年龄低于 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。
之间的差异throw
和throws
:
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:
|
Syntax:
|
详细了解我们的异常Java Try..Catch 教程。
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!