เราควรสร้าง exception ของตัวเองใน Java จำจุดต่อไปนี้ไว้เมื่อเขียน exception classes ของเราเอง
- Exceptions ทุกตัวต้องเป็นลูกของ Throwable
- ถ้าเราต้องการเขียน checked exception ที่บังคับโดย Handle or Declare Rule เราต้อง extend Exception class
- ถ้าเราต้องการเขียน runtime exception เราต้อง extend RuntimeException class
เราสามารถกำหนด Exception class ของตัวเองได้ดังนี้:
class MyException extends Exception { }
เราเพียงแค่ extend Exception class เพื่อสร้าง Exception class ของตัวเอง นี่ถือว่าเป็น checked exceptions คลาส InsufficientFundsException ต่อไปนี้เป็น user-defined exception ที่ extend Exception class ทำให้เป็น checked 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)