288、Java中级05 - 异常处理【自定义异常】 2019.12.03

1、创建自定义异常

一个英雄攻击另一个英雄的时候,如果发现另一个英雄已经挂了,就会抛出EnemyHeroIsDeadException
创建一个类EnemyHeroIsDeadException,并继承Exception
提供两个构造方法

  1. 无参的构造方法
  2. 带参的构造方法,并调用父类的对应的构造方法
class EnemyHeroIsDeadException extends Exception{
     
    public EnemyHeroIsDeadException(){
         
    }
    public EnemyHeroIsDeadException(String msg){
        super(msg);
    }
}

2、抛出自定义异常

在Hero的attack方法中,当发现敌方英雄的血量为0的时候,抛出该异常

  1. 创建一个EnemyHeroIsDeadException实例
  2. 通过throw 抛出该异常
  3. 当前方法通过 throws 抛出该异常

在外部调用attack方法的时候,就需要进行捕捉,并且捕捉的时候,可以通过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();
        }
         
    }
}

3、练习:自定义异常

对MyStringBuffer的插入和删除方法中的边界条件判断,用抛出异常来解决
例: insert(int pos, String b) , 当pos 是负数的时候,抛出自定义异常
需要实现自定义两种异常
IndexIsNagetiveException 下标为负异常
IndexIsOutofRangeException 下标超出范围异常
以下是需要调用这些异常的场景:

  • pos<0

抛出 IndexIsNagetiveException

  • pos>length

抛出 IndexIsOutofRangeException

  • null==b

抛出 NullPointerException

  • start<0

抛出 IndexIsNagetiveException

  • start>length

抛出 IndexIsOutofRangeException

  • end<0

抛出 IndexIsNagetiveException

  • end>length

抛出 IndexIsOutofRangeException

  • start>=end

抛出 IndexIsOutofRangeException

注意: 接口IStringBuffer中声明的方法需要抛出异常

package StringBuffer;
 
public class MyStringBuffer2 {
 
    //  数组容量
    int capacity = 16;
    int length = 0;
    char[] value;
     
    public MyStringBuffer2() {
        value = new char[capacity];
    }
     
    public MyStringBuffer2(String str) {
        this();
        if (null == str)
            return;
  
        if (capacity < str.length()) {
            capacity = value.length * 2;
            value = new char[capacity];
        }
  
        if (capacity >= str.length())
            System.arraycopy(str.toCharArray(), 0, value, 0, str.length());
  
        length = str.length();
    }
     
    public void append(String str) throws Exception{
        insert(length, str);
    }
 
    public void append(char c) throws Exception{
        append(String.valueOf(c));
    }
 
    public void insert(int pos, char b) throws Exception{
        insert(pos, String.valueOf(b));
    }
 
    public void insert(int pos, String b) throws Exception{
        // 边界判断
        if(pos<0)
            throw new IndexIsNagetiveException("下标为负异常!!");
        if(pos>length)
            throw new IndexIsOutofRangeException("下标超出范围异常!!");
        if(null==b)
            throw new NullPointerException("空字符串异常!!");
        // 扩容
        while(length+b.length()>capacity) {
            capacity = (int)((length+b.length())*1.5);
            char[] newValue = new char[capacity];
            System.arraycopy(value, 0, newValue, 0, length);
            value = newValue;
        }
        char[] cs = b.toCharArray();
          
            //先把已经存在的数据往后移
            System.arraycopy(value, pos, value,pos+ cs.length, length-pos);
            //把要插入的数据插入到指定位置
            System.arraycopy(cs, 0, value, pos, cs.length);
            length = length+cs.length;
    }
 
    public void delete(int start) throws Exception{
        delete(start,length);
    }
 
    public void delete(int start, int end) throws Exception{
        if(start<0||end<0)
            throw new IndexIsNagetiveException("下标为负异常");
        if(start>length||end>length||start>=end)
            throw new IndexIsOutofRangeException("下标超出范围异常");
        System.arraycopy(value, end, value, start, length-end);
        length-=end-start;
    }
 
    public void reverse() {
        for(int i = 0;i<length/2;i++) {
            char temp = value[i];
            value[i] = value[length-i-1];
            value[length-i-1] = temp;
        }
    }
 
    public int length() {
        return length;
    }
     
    public String toString() {
        char[] realValue = new char[length];
        System.arraycopy(value, 0, realValue, 0, length);
        return new String(realValue);
    }
     
    class IndexIsNagetiveException extends Exception {
        public IndexIsNagetiveException() {
              
        }
        public IndexIsNagetiveException(String msg) {
            super (msg);
        }
    }
    class IndexIsOutofRangeException extends Exception{
        public IndexIsOutofRangeException() {           
        }
        public IndexIsOutofRangeException(String msg) {
            super (msg);
        }
    }
     
    public static void main(String[] args) {
         
        MyStringBuffer2 str1 = new MyStringBuffer2("终极无敌嗜血封魔手!!");
        System.out.println(str1);
        try {
            str1.insert(-1, '1');
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println("具体异常为:"+e.getMessage());
            e.printStackTrace();
        }
        try {
            str1.delete(1,2424);
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println("具体异常为:"+e.getMessage());
            e.printStackTrace();
        }
         
    }
 
}

4、参考链接

[01] How2j - 异常处理系列教材 (五)- JAVA 自定义异常

发布了309 篇原创文章 · 获赞 229 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/youyouwuxin1234/article/details/103353420