สร้าง Custom Unchecked Exception โดย extends RuntimeException
ไวยากรณ์พื้นฐาน
public class MyCustomException extends RuntimeException {
public MyCustomException(String message) {
super(message);
}
}
การ Implement แบบสมบูรณ์ (4 Constructors)
public class CustomUncheckedException extends RuntimeException {
// 1. Constructor รับ message
public CustomUncheckedException(String message) {
super(message);
}
// 2. Constructor wrap exception (cause)
public CustomUncheckedException(Throwable cause) {
super(cause);
}
// 3. Constructor รับ message และ cause
public CustomUncheckedException(String message, Throwable throwable) {
super(message, throwable);
}
// 4. No-arg constructor (optional)
public CustomUncheckedException() {
super();
}
}
คำอธิบายแต่ละ Constructor
| Constructor | ใช้เมื่อไหร่ |
|---|---|
| String message | throw new MyEx("Custom message") |
| Throwable cause | catch(e) { throw new MyEx(e); } wrap exception เดิม |
| String message, Throwable cause | catch(e) { throw new MyEx("msg", e); } ทั้ง message และ cause |
| No-arg | throw new MyEx() ไม่มี message |
ความแตกต่าง Checked vs Unchecked
- Checked Exception - extends Exception (แต่ไม่ใช่ RuntimeException) - Compiler บังคับ handle
- Unchecked Exception - extends RuntimeException - Compiler ไม่บังคับ handle
- Unchecked มักเกิดจาก Programming Error (null pointer, index out of bounds, illegal argument)
ตัวอย่างการใช้งาน
public class BankAccount {
private double balance;
public void withdraw(double amount) {
if (amount > balance) {
throw new InsufficientFundsException(
"Insufficient funds: " + balance + " requested: " + amount
);
}
balance -= amount;
}
}
// Custom Unchecked Exception
class InsufficientFundsException extends RuntimeException {
public InsufficientFundsException(String message) {
super(message);
}
}