JAVA自定义异常
定义一个异常OverdraftException: 透支异常,继承Exception
public class OverdraftExcption extends Exception {
double deficit;
public OverdraftExcption(String msg,double deficit){
super(msg);
this.deficit = deficit;
}
public double getDeficit() {
return this.deficit;
}
}
定义一个Account父类
Account类: 银行账号
属性: balance 余额
方法: getBalance() 获取余额
方法: deposit() 存钱
方法: withdraw() 取钱
属性: deficit 透支额
代码如下
public class Accout {
int init;
double balance;
public Accout(int init,double balance){
this.init = init;
this.balance = balance;
}
public double getBalance() {
return this.balance;
}
public double deposit(double amt) {
System.out.println(this.init + "账户进行存钱额度为" + amt);
this.balance = this.balance + amt;
return this.balance;
}
public double withdraw(double amt) throws OverdraftExcption{
if(this.balance < amt){
throw new OverdraftExcption("余额不足",amt - this.balance);
}else{
this.balance = this.balance - amt;
}
return amt;
}
}
定义一个继承Account的子类CheckingAccount 可透支余额账号
类: CheckingAccount 支票账户,具备透支额度,继承Account
属性:overdraftProtection 透支额度
public class CheckingAccount extends Accout {
double ouverdraftProtection;
public CheckingAccount(int init, double balance,double ouverdraftProtection) {
super(init, balance);
this.ouverdraftProtection = ouverdraftProtection;
}
public double withdraw(double amt) throws OverdraftExcption{
if(this.balance < amt){
if(amt - this.balance > this.ouverdraftProtection){
throw new OverdraftExcption("错误操作原因:超出额度",(amt - this.balance)-this.ouverdraftProtection);
}else {
this.balance = this.balance - amt;
}
}else {
this.balance = this.balance - amt;
}
return amt;
}
}
执行代码
public class start {
public static void main(String[] args) {
Accout accout = new Accout(123123,1000);
CheckingAccount caccount = new CheckingAccount(111,10000,1000);
System.out.println(accout.init+"账户的存款有"+accout.getBalance());
System.out.println(caccount.init+"账户的存款有"+caccount.getBalance()+"可预支额度为"+caccount.ouverdraftProtection);
System.out.println(accout.deposit(100));
try {
System.out.println("提款:"+accout.withdraw(1200));
}catch (OverdraftExcption e){
System.out.println("操作错误原因:"+e.getMessage());
System.out.println("超出余额"+e.getDeficit());
}
try {
System.out.println("提款:"+caccount.withdraw(12000));
}catch (OverdraftExcption e){
System.out.println(e.getMessage());
System.out.println("超出额度"+e.getDeficit());
}
System.out.println(caccount.init+"账户的存款有"+caccount.getBalance());
System.out.println(accout.init+"账户的存款有"+accout.getBalance());
}
}
结果如下