Java พ่นคำสำคัญ
ตัวอย่าง
โยนข้อยกเว้นถ้าอายุต่ำกว่า 18 (พิมพ์ "การเข้าถึงถูกปฏิเสธ") หากอายุ 18 ปีขึ้นไป ให้พิมพ์ "สิทธิ์การเข้าถึง":
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 |
---|---|
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 Tutorialของเรา