Throwable class เป็น superclass ของ errors และ exceptions ทั้งหมดใน Java Objects ที่เป็น instances ของคลาสนี้ถูกโยนโดย Java Virtual Machine หรือสามารถโยนโดย throw statement ได้ เช่นเดียวกัน คลาสนี้หรือ subclass หนึ่งของมันสามารถเป็น argument type ใน catch clause ได้
Instances ของสอง subclass Error และ Exception ใช้ระบุว่าสถานการณ์พิเศษ (exceptional situations) ได้เกิดขึ้น instances เหล่านี้ถูกสร้างใน context ของสถานการณ์พิเศษเพื่อรวมข้อมูลที่เกี่ยวข้อง
Exception methods ที่ใช้บ่อยของ Throwable class
- public String getMessage(): คืนค่า message string เกี่ยวกับ exception
- public Throwable getCause(): คืนค่าสาเหตุของ exception จะคืน null หากสาเหตุไม่ทราบหรือไม่มี
- public String toString(): คืนค่าคำอธิบายสั้นของ exception
- public void printStackTrace(PrintStream s): พิมพ์คำอธิบายสั้นของ exception (ใช้ toString()) + stack trace สำหรับ exception นี้บน error output stream (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)