Java self - exception handling custom exception

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

  1. No argument constructor
  2. 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

  1. Create an instance of EnemyHeroIsDeadException
  2. By throw Thrown
  3. 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 ()
Throw custom exception

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();
      }
       
  }
}

Guess you like

Origin www.cnblogs.com/jeddzd/p/11691151.html