1、如何定義自己的異常
Java支持自己創建的異常。瞭解異常看這裏:什麼是java中的異常
方法如下:
1、所有的異常必須是Throwable的子類。
2、如果想寫一個檢查異常,需要擴展Exception類。
3、如果想編寫一個運行時異常,則需要擴展RuntimeException類。
4、異常類與任何其他類一樣,可以包含字段和方法。
我們可以定義如下自己的異常處理類:
-
class MyException extends Exception{
-
}
例子:
-
import java.io.*;
-
-
public class InsufficientFundsException extends Exception
-
{
-
private double amount;
-
public InsufficientFundsException(double amount)
-
{
-
this.amount = amount;
-
}
-
public double getAmount()
-
{
-
return amount;
-
}
-
}
爲了證明我們的使用用戶定義的異常,下面的CheckingAccount類包含一個withdraw()方法拋出一個InsufficientFundsException。
-
import java.io.*;
-
-
public 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;
-
}
-
}
下面BankDemo程序演示調用deposit()和withdraw() 方法。
-
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("
-
Withdrawing $100...");
-
c.withdraw(100.00);
-
System.out.println("
-
Withdrawing $600...");
-
c.withdraw(600.00);
-
}catch(InsufficientFundsException e)
-
{
-
System.out.println("Sorry, but you are short $"
-
+ e.getAmount());
-
e.printStackTrace();
-
}
-
}
-
}
編譯所有上述三個文件並運行BankDemo,這將產生以下結果:
Depositing $500...
Withdrawing $100...
Withdrawing $600...
Sorry, but you are short $200.0
InsufficientFundsException
at CheckingAccount.withdraw(CheckingAccount.java:25)
at BankDemo.main(BankDemo.java:13)