Java self study - exception handling custom exception

Posted by vexusdev on Thu, 17 Oct 2019 23:55:50 +0200

Java custom exception

Example 1: create a custom exception

When a hero attacks another hero, if he finds that another hero has already hung up, he will throw an EnemyHeroIsDeadException
Create a class EnemyHeroIsDeadException and inherit the Exception
Two construction methods are provided

  1. Construction method without parameters
  2. Construct method with parameters and call the corresponding constructor of the parent class
class EnemyHeroIsDeadException extends Exception{
     
    public EnemyHeroIsDeadException(){
         
     }
    public EnemyHeroIsDeadException(String msg){
        super(msg);
    }
}

Example 2: throw a custom exception

In Hero's attack method, this exception is thrown when the enemy Hero's HP is found to be 0

  1. Create an instance of EnemyHeroIsDeadException
  2. Throw the exception through throw
  3. The current method throws the exception through throws

When the attack method is called externally, it needs to be captured. When capturing, you can get the specific reason for the error through 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 + " It has been hung up.,No need to cast skills" );
      }
  }

  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 = "Galen";
      garen.hp = 616;

      Hero teemo =  new Hero();
      teemo.name = "Ti Mo";
      teemo.hp = 0;
       
      try {
          garen.attackHero(teemo);
           
      } catch (EnemyHeroIsDeadException e) {
          // TODO Auto-generated catch block
          System.out.println("Specific cause of abnormality:"+e.getMessage());
          e.printStackTrace();
      }
       
  }
}

Topics: Java