Java throws 關鍵字
示例
如果 age 小於 18,則丟擲異常(列印 "Access denied")。如果 age 為 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
等。
throw
和 throws
的區別
throw | throws |
---|---|
用於為方法丟擲異常 | 用於指示方法可能丟擲的異常型別 |
不能丟擲多個異常 | 可以宣告多個異常 |
語法
|
語法
|
相關頁面
在我們的 Java Try..Catch 教程 中瞭解更多關於異常的資訊。