码迷,mamicode.com
首页 > 编程语言 > 详细

Java技术_Java千百问(0025)_如何自定义异常

时间:2016-04-10 15:01:18      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:

点击进入_更多_Java千百问


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)


Java技术_Java千百问(0025)_如何自定义异常

标签:

原文地址:http://blog.csdn.net/ooppookid/article/details/51106457

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!