เราควรสร้างข้อยกเว้นของเราเองใน Java โปรดคำนึงถึงประเด็นต่อไปนี้เมื่อเขียนคลาสข้อยกเว้นของเราเอง
- ข้อยกเว้นทั้งหมดต้องเป็นลูกของ Throwable
- หากเราต้องการเขียนข้อยกเว้นที่เลือกซึ่งบังคับใช้โดยอัตโนมัติโดย Handle หรือ Declare Rule เราจำเป็นต้องขยายคลาส Exception
- หากเราต้องการเขียนข้อยกเว้นรันไทม์ เราจำเป็นต้องขยายคลาส RuntimeException
เราสามารถกำหนดคลาส Exception ของเราเองได้ดังนี้:
class MyException extends Exception {
} เราเพียงแค่ต้องขยายคลาส Exception เพื่อสร้างคลาส Exception ของเราเอง สิ่งเหล่านี้ถือเป็นข้อยกเว้นการตรวจสอบ คลาส InsufficentFundsException ต่อไปนี้เป็นข้อยกเว้นที่ผู้ใช้กำหนดเองซึ่งขยายคลาส Exception ทำให้เป็นข้อยกเว้นที่ตรวจสอบแล้ว
ตัวอย่าง
// File Name InsufficientFundsException.java
import java.io.*;
class InsufficientFundsException extends Exception {
private double amount;
public InsufficientFundsException(double amount) {
this.amount = amount;
}
public double getAmount() {
return amount;
}
}
// File Name CheckingAccount.java
class CheckingAccount {
private double balance;
private int number;
public CheckingAccount(int number) {
this.number = number;
}
public void deposit(double amount) {
balance += amount;
}
public void withdraw(double amount) throws InsufficientFundsException {
if(amount <= balance) {
balance -= amount;
}
else {
double needs = amount - balance;
throw new InsufficientFundsException(needs);
}
}
public double getBalance() {
return balance;
}
public int getNumber() {
return number;
}
}
// File Name BankDemo.java
public class BankDemo {
public static void main(String [] args) {
CheckingAccount c = new CheckingAccount(101);
System.out.println("Depositing $500...");
c.deposit(500.00);
try {
System.out.println("\nWithdrawing $100...");
c.withdraw(100.00);
System.out.println("\nWithdrawing $600...");
c.withdraw(600.00);
} catch(InsufficientFundsException e) {
System.out.println("Sorry, but you are short $" + e.getAmount());
e.printStackTrace();
}
}
}
ผลลัพธ์
Depositing $500... Withdrawing $100... Withdrawing $600... Sorry, but you are short $200.0 InsufficientFundsException at CheckingAccount.withdraw(BankDemo.java:32) at BankDemo.main(BankDemo.java:53)