异常处理(005)_如何自定义异常

1、如何定义自己的异常

Java支持自己创建的异常。了解异常看这里:什么是java中的异常

方法如下:

1、所有的异常必须是Throwable的子类。
2、如果想写一个检查异常,需要扩展Exception类
3、如果想编写一个运行时异常,则需要扩展RuntimeException类
4、异常类与任何其他类一样,可以包含字段方法
我们可以定义如下自己的异常处理类:
[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. class MyException extends Exception{  
  2. }  
例子:
[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. import java.io.*;  
  2.   
  3. public class InsufficientFundsException extends Exception  
  4. {  
  5. private double amount;  
  6. public InsufficientFundsException(double amount)  
  7. {  
  8. this.amount = amount;  
  9. }  
  10. public double getAmount()  
  11. {  
  12. return amount;  
  13. }  
  14. }  
为了证明我们的使用用户定义的异常,下面的CheckingAccount类包含一个withdraw()方法抛出一个InsufficientFundsException。
[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. import java.io.*;  
  2.   
  3. public class CheckingAccount  
  4. {  
  5. private double balance;  
  6. private int number;  
  7. public CheckingAccount(int number)  
  8. {  
  9. this.number = number;  
  10. }  
  11. public void deposit(double amount)  
  12. {  
  13. balance += amount;  
  14. }  
  15. public void withdraw(double amount) throws  
  16. InsufficientFundsException  
  17. {  
  18. if(amount <= balance)  
  19. {  
  20. balance -= amount;  
  21. }  
  22. else  
  23. {  
  24. double needs = amount - balance;  
  25. throw new InsufficientFundsException(needs);  
  26. }  
  27. }  
  28. public double getBalance()  
  29. {  
  30. return balance;  
  31. }  
  32. public int getNumber()  
  33. {  
  34. return number;  
  35. }  
  36. }  
下面BankDemo程序演示调用deposit()和withdraw() 方法。
[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public class BankDemo  
  2. {  
  3. public static void main(String [] args)  
  4. {  
  5. CheckingAccount c = new CheckingAccount(101);  
  6. System.out.println("Depositing $500...");  
  7. c.deposit(500.00);  
  8. try  
  9. {  
  10. System.out.println("  
  11. Withdrawing $100...");  
  12. c.withdraw(100.00);  
  13. System.out.println("  
  14. Withdrawing $600...");  
  15. c.withdraw(600.00);  
  16. }catch(InsufficientFundsException e)  
  17. {  
  18. System.out.println("Sorry, but you are short $"  
  19. + e.getAmount());  
  20. e.printStackTrace();  
  21. }  
  22. }  
  23. }  
编译所有上述三个文件并运行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)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章