บางครั้งจำเป็นต้องพัฒนาข้อยกเว้นที่มีความหมายตามความต้องการของแอปพลิเคชัน เราสามารถสร้างข้อยกเว้นของตัวเองได้โดยการขยายคลาส Exception ใน Java
ข้อยกเว้นที่ผู้ใช้กำหนดเองใน Java ยังเรียกว่า Custom Exceptions
ขั้นตอนการสร้าง Custom Exception พร้อมตัวอย่าง
- คลาส
CustomExceptionเป็นคลาสข้อยกเว้นกำหนดเอง ซึ่งขยายจากคลาสException - สร้างตัวแปรท้องถิ่น
messageเพื่อเก็บข้อความข้อยกเว้นในออบเจ็กต์คลาส - เราส่งอาร์กิวเมนต์สตริงไปยังคอนสตรัคเตอร์ของออบเจ็กต์ custom exception คอนสตรัคเตอร์ตั้งค่าสตริงอาร์กิวเมนต์ให้กับสตริงส่วนตัว
message - เมธอด
toString()ใช้สำหรับพิมพ์ข้อความข้อยกเว้น - เราเพียงแค่โยน
CustomExceptionโดยใช้บล็อก try-catch หนึ่งบล็อกในเมธอด main และสังเกตว่าสตริงถูกส่งอย่างไรขณะสร้าง custom exception ภายในบล็อก catch เราพิมพ์ข้อความออกมา
ตัวอย่าง
class CustomException extends Exception { String message; CustomException(String str) { message = str; } public String toString() { return ("Custom Exception Occurred : " + message); } } public class MainException { public static void main(String args[]) { try { throw new CustomException("This is a custom message"); } catch(CustomException e) { System.out.println(e); } } }ผลลัพธ์
Custom Exception Occurred : This is a custom message