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 教程 中瞭解更多關於異常的資訊。