ไม่สามารถ เราไม่สามารถวางโค้ดใดๆ หลัง throw statement ได้ จะทำให้เกิด compile-time error: Unreachable Statement
Throw Keyword ใน Java
- throw keyword ใช้เพื่อโยน exception ด้วยตนเอง (manually)
- เมื่อจำเป็นต้องระงับการทำงานของฟังก์ชันตาม เงื่อนไขข้อผิดพลาดที่ผู้ใช้กำหนด (user-defined logical error) เราจะใช้ throw keyword เพื่อโยน exception
- เราต้องจัดการ exception เหล่านี้โดยใช้ try-catch blocks
กฎการใช้ throw keyword ใน Java
- throw keyword ต้องตามด้วยออบเจ็กต์ชนิด Throwable
- throw keyword ต้องใช้เฉพาะใน logic ของเมธอดเท่านั้น
- เนื่องจากเป็น transfer statement เราจึงไม่สามารถวางคำสั่งหลัง throw statement ได้ จะทำให้เกิด compile-time error: Unreachable code
- เราสามารถโยน user-defined และ predefined exceptions ได้โดยใช้ throw keyword
ตัวอย่าง
public class ThrowKeywordDemo {
public static void main(String[] args) {
try {
throw new ArithmeticException();
System.out.println("In try block"); // compile-time error, unreachable statement
} catch (Exception e) {
System.out.println(e);
e.printStackTrace();
}
}
}
โค้ดด้านบน ไม่สามารถทำงานได้ เพราะมีคำสั่งหลัง throw statement ใน try block ซึ่งทำให้เกิด compile-time error ดังนั้นเราจึงไม่สามารถวางคำสั่งใดๆ หลัง throw statement ใน Java ได้
ผลลัพธ์
unreachable statement
System.out.println("In try block");