เราสามารถสร้าง ไม่ได้เลือก . ที่กำหนดเองได้ ข้อยกเว้น โดยขยาย RuntimeException ใน Java
ไม่ถูกเลือก ข้อยกเว้น รับช่วงจาก ข้อผิดพลาด คลาสหรือ RuntimeException ระดับ. โปรแกรมเมอร์หลายคนรู้สึกว่าเราไม่สามารถจัดการกับข้อยกเว้นเหล่านี้ในโปรแกรมของเราได้ เนื่องจากเป็นข้อผิดพลาดประเภทที่โปรแกรมไม่สามารถกู้คืนได้ในขณะที่โปรแกรมกำลังทำงานอยู่ เมื่อมีการส่งข้อยกเว้นที่ไม่ได้ตรวจสอบ มักเกิดจากการใช้รหัสในทางที่ผิด , ผ่านค่า null หรืออาร์กิวเมนต์ไม่ถูกต้อง .
ไวยากรณ์
public class MyCustomException extends RuntimeException {
public MyCustomException(String message) {
super(message);
}
} การนำข้อยกเว้นที่ไม่ได้ตรวจสอบไปใช้
การปรับใช้ข้อยกเว้นที่ไม่ได้ตรวจสอบแบบกำหนดเองนั้นเกือบจะคล้ายกับข้อยกเว้นที่ตรวจสอบแล้วใน Java ข้อแตกต่างเพียงอย่างเดียวคือข้อยกเว้นที่ไม่ได้ตรวจสอบจะต้องขยาย RuntimeException แทนที่จะเป็นข้อยกเว้น
ตัวอย่าง
public class CustomUncheckedException extends RuntimeException {
/*
* Required when we want to add a custom message when throwing the exception
* as throw new CustomUncheckedException(" Custom Unchecked Exception ");
*/
public CustomUncheckedException(String message) {
// calling super invokes the constructors of all super classes
// which helps to create the complete stacktrace.
super(message);
}
/*
* Required when we want to wrap the exception generated inside the catch block and rethrow it
* as catch(ArrayIndexOutOfBoundsException e) {
* throw new CustomUncheckedException(e);
* }
*/
public CustomUncheckedException(Throwable cause) {
// call appropriate parent constructor
super(cause);
}
/*
* Required when we want both the above
* as catch(ArrayIndexOutOfBoundsException e) {
* throw new CustomUncheckedException(e, "File not found");
* }
*/
public CustomUncheckedException(String message, Throwable throwable) {
// call appropriate parent constructor
super(message, throwable);
}
}