โยนได้ class เป็น superclass ของข้อผิดพลาดและข้อยกเว้นทั้งหมดใน Java ออบเจ็กต์ที่เป็นอินสแตนซ์ของคลาสนี้ถูกส่งโดย Java Virtual Machine หรือสามารถโยนโดย โยน คำแถลง. ในทำนองเดียวกัน คลาสนี้หรือหนึ่งในคลาสย่อยของคลาสนี้สามารถเป็นประเภทอาร์กิวเมนต์ใน catch clause ได้
อินสแตนซ์ของสองคลาสย่อย ข้อผิดพลาด และ ข้อยกเว้น ใช้เพื่อระบุว่ามีสถานการณ์พิเศษเกิดขึ้น ตัวอย่างเหล่านี้ถูกสร้างขึ้นในบริบทของสถานการณ์พิเศษเพื่อรวมข้อมูลที่เกี่ยวข้องไว้ด้วย
วิธีการยกเว้นที่ใช้กันทั่วไปของคลาส Throwable
- สตริงสาธารณะ getMessage(): ส่งคืนสตริงข้อความเกี่ยวกับข้อยกเว้น
- สาธารณะ Throwable getCause(): ส่งคืนสาเหตุของข้อยกเว้น มันจะคืนค่า null หากไม่ทราบสาเหตุหรือไม่มีอยู่จริง
- สตริงสาธารณะ toString(): ส่งคืนคำอธิบายสั้น ๆ ของข้อยกเว้น
- โมฆะสาธารณะ printStackTrace(PrintStream s): พิมพ์คำอธิบายสั้น ๆ ของข้อยกเว้น (โดยใช้ toString()) + การติดตามสแต็กสำหรับข้อยกเว้นนี้ในสตรีมเอาต์พุตข้อผิดพลาด (System.err)
ตัวอย่าง
class ArithmaticTest {
public void division(int num1, int num2) {
try {
//java.lang.ArithmeticException here.
System.out.println(num1/num2);
//catch ArithmeticException here.
} catch(ArithmeticException e) {
//print the message string about the exception.
System.out.println("getMessage(): " + e.getMessage());
//print the cause of the exception.
System.out.println("getCause(): " + e.getCause());
//print class name + “: “ + message.
System.out.println("toString(): " + e.toString());
System.out.println("printStackTrace(): ");
//prints the short description of the exception + a stack trace for this exception.
e.printStackTrace();
}
}
}
public class Test {
public static void main(String args[]) {
//creating ArithmaticTest object
ArithmaticTest test = new ArithmaticTest();
//method call
test.division(20, 0);
}
} ผลลัพธ์
getMessage(): / by zero getCause(): null toString(): java.lang.ArithmeticException: / by zero printStackTrace(): java.lang.ArithmeticException: / by zero at ArithmaticTest.division(Test.java:5) at Test.main(Test.java:27)