自定义异常和综合练习
package Exception_test;
public class Hero {
public String name;
protected float hp;
//方法抛出异常
public void attackHero(Hero h) throws EnemyHeroIsDeadException{
if(h.hp==0)throw new EnemyHeroIsDeadException(h.name+"挂了 不需要施放技能");
}
public String toString(){
return name;
}
//自定义异常类 继承Exception
class EnemyHeroIsDeadException extends Exception{
public EnemyHeroIsDeadException(){}
public EnemyHeroIsDeadException(String msg){super(msg);}
}
public static void main(String[] args){
Hero zuque=new Hero();
zuque.name="朱雀";
zuque.hp=44;
Hero lulu=new Hero();
lulu.name="鲁鲁";
lulu.hp=0;//鲁鲁的血量=0
try {
zuque.attackHero(lulu);
}catch (EnemyHeroIsDeadException e){
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
运行结果
综合练习
这是一个类图
Account类: 银行账号
属性: balance 余额
方法: getBalance() 获取余额
方法: deposit() 存钱
方法: withdraw() 取钱
OverdraftException: 透支异常,继承Exception
属性: deficit 透支额
public class Account {
protected double balance;//余额
public double getBalance() {
return balance;
}
//存钱
public void deposit(double amt) {
this.balance = this.balance + amt;
}
//取钱
public void withdraw(double amt) throws OverdraftException {//抛出自定义异常 throws用在方法声明时
if (this.balance - amt < 0) {//余额<要取款的钱
throw new OverdraftException("余额不足,超出的额度是:", amt - this.balance);//throw方法在方法中使用
}
}
public Account(double balance) {
this.balance = balance;
}
//透支异常
class OverdraftException extends Exception {
private double deficit;//透支额度
public OverdraftException(String message, double deficit) {
super(message);//打印错误信息
this.deficit = deficit;//定义透支额度
}
public double getDeficit() {
return deficit;
}
}
public static void main(String args[]) {
Account account = new Account(30);
try {
account.withdraw(100); //try catch捕捉异常
} catch (OverdraftException overdraftException) {
System.out.print(overdraftException.getMessage());
System.out.println(overdraftException.getDeficit());
overdraftException.printStackTrace();
}
}
}