Chúng ta nên tạo exception riêng trong Java. Hãy nhớ các điểm sau khi viết exception class của mình
- Tất cả exceptions phải là con của Throwable.
- Nếu muốn viết checked exception được enforced tự động bởi Handle or Declare Rule, cần extend Exception class.
- Nếu muốn viết runtime exception, cần extend RuntimeException class.
Chúng ta có thể định nghĩa Exception class riêng như sau:
class MyException extends Exception { }Chỉ cần extend Exception class để tạo Exception class riêng. Những này được coi là checked exceptions. Class InsufficientFundsException sau là user-defined exception extend Exception class, làm cho nó trở thành checked exception.
Ví dụ
// 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();
}
}
} Kết quả
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)