Java custom exception
Example 1: Create a custom exception
A hero attack another hero of the time, if we find another hero has hung up, will throw EnemyHeroIsDeadException
create a class EnemyHeroIsDeadException, and inherit Exception
provides two constructors
- No argument constructor
- Parameterized constructor and calling the corresponding parent class constructor
class EnemyHeroIsDeadException extends Exception{
public EnemyHeroIsDeadException(){
}
public EnemyHeroIsDeadException(String msg){
super(msg);
}
}
Example 2: throw custom exception
In the attack method Hero, when found in blood enemy hero to zero when Thrown
- Create an instance of EnemyHeroIsDeadException
- By throw Thrown
- The current method throws Thrown
When the external call attack method when you need to capture, and capture, can get specific reason for the error was by e.getMessage ()
package charactor;
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;
}
class EnemyHeroIsDeadException extends Exception{
public EnemyHeroIsDeadException(){
}
public EnemyHeroIsDeadException(String msg){
super(msg);
}
}
public static void main(String[] args) {
Hero garen = new Hero();
garen.name = "盖伦";
garen.hp = 616;
Hero teemo = new Hero();
teemo.name = "提莫";
teemo.hp = 0;
try {
garen.attackHero(teemo);
} catch (EnemyHeroIsDeadException e) {
// TODO Auto-generated catch block
System.out.println("异常的具体原因:"+e.getMessage());
e.printStackTrace();
}
}
}