how2j.cn

本视频是解读性视频,所以希望您已经看过了本知识点的内容,并且编写了相应的代码之后,带着疑问来观看,这样收获才多。 不建议一开始就观看视频



4分55秒
本视频采用html5方式播放,如无法正常播放,请将浏览器升级至最新版本,推荐火狐,chrome,360浏览器 如果装有迅雷,播放视频呈现直接下载状态,请调整 迅雷系统设置-基本设置-启动-监视全部浏览器 (去掉这个选项)



示例 1 : 创建自定义异常   
示例 2 : 抛出自定义异常   
示例 3 : 练习-自定义异常   
示例 4 : 答案-自定义异常   

示例 1 :

创建自定义异常

一个英雄攻击另一个英雄的时候,如果发现另一个英雄已经挂了,就会抛出EnemyHeroIsDeadException
创建一个类EnemyHeroIsDeadException,并继承Exception
提供两个构造方法
1. 无参的构造方法
2. 带参的构造方法,并调用父类的对应的构造方法
class EnemyHeroIsDeadException extends Exception{ public EnemyHeroIsDeadException(){ } public EnemyHeroIsDeadException(String msg){ super(msg); } }
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 :

练习-自定义异常

Or  姿势不对,事倍功半! 点击查看做练习的正确姿势
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中声明的方法需要抛出异常
示例 4 :

答案-自定义异常

在查看答案前,尽量先自己完成,碰到问题再来查看答案,收获会更多
本视频是解读性视频,所以希望您已经看过了本答案的内容,带着疑问来观看,这样收获才多。 不建议一开始就观看视频

4分51秒 本视频采用html5方式播放,如无法正常播放,请将浏览器升级至最新版本,推荐火狐,chrome,360浏览器 如果装有迅雷,播放视频呈现直接下载状态,请调整 迅雷系统设置-基本设置-启动-监视全部浏览器 (去掉这个选项)


package exception; public class IndexIsNagetiveException extends Exception{ }
package exception; public class IndexIsOutofRangeException extends Exception { }
package character; import exception.IndexIsNagetiveException; import exception.IndexIsOutofRangeException; public interface IStringBuffer { public void append(String str) throws IndexIsOutofRangeException, IndexIsNagetiveException; ; //追加字符串 public void append(char c) throws IndexIsOutofRangeException, IndexIsNagetiveException; ; //追加字符 public void insert(int pos,char b) throws IndexIsOutofRangeException, IndexIsNagetiveException; //指定位置插入字符 public void insert(int pos,String b) throws IndexIsOutofRangeException, IndexIsNagetiveException; ; //指定位置插入字符串 public void delete(int start) throws IndexIsOutofRangeException, IndexIsNagetiveException; ; //从开始位置删除剩下的 public void delete(int start,int end) throws IndexIsOutofRangeException, IndexIsNagetiveException; ; //从开始位置删除结束位置-1 public void reverse(); //反转 public int length(); //返回长度 }
package character; import exception.IndexIsNagetiveException; import exception.IndexIsOutofRangeException; public class MyStringBuffer implements IStringBuffer { int capacity = 16; int length = 0; char[] value; public MyStringBuffer() { value = new char[capacity]; } // 有参构造方法 public MyStringBuffer(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(); } @Override public void append(String str) throws IndexIsNagetiveException, IndexIsOutofRangeException { insert(length, str); } @Override public void append(char c) throws IndexIsNagetiveException, IndexIsOutofRangeException { append(String.valueOf(c)); } @Override public void insert(int pos, char b) throws IndexIsNagetiveException, IndexIsOutofRangeException { insert(pos, String.valueOf(b)); } @Override public void delete(int start) throws IndexIsNagetiveException, IndexIsOutofRangeException { delete(start, length); } @Override public void delete(int start, int end) throws IndexIsNagetiveException, IndexIsOutofRangeException { // 边界条件判断 if (start < 0) throw new IndexIsNagetiveException(); if (start > length) throw new IndexIsOutofRangeException(); if (end < 0) throw new IndexIsNagetiveException(); if (end > length) throw new IndexIsOutofRangeException(); if (start >= end) throw new IndexIsOutofRangeException(); System.arraycopy(value, end, value, start, length - end); length -= end - start; } @Override 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; } } @Override public int length() { // TODO Auto-generated method stub return length; } @Override public void insert(int pos, String b) throws IndexIsNagetiveException, IndexIsOutofRangeException { // 边界条件判断 if (pos < 0) throw new IndexIsNagetiveException(); if (pos > length) throw new IndexIsOutofRangeException(); if (null == b) throw new NullPointerException(); // 扩容 if (length + b.length() > capacity) { capacity = (int) ((length + b.length()) * 2.5f); 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 String toString() { char[] realValue = new char[length]; System.arraycopy(value, 0, realValue, 0, length); return new String(realValue); } public static void main(String[] args) { try { MyStringBuffer sb = new MyStringBuffer("there light"); System.out.println(sb); sb.insert(0, "let "); System.out.println(sb); sb.insert(10, "be "); System.out.println(sb); sb.insert(0, "God Say:"); System.out.println(sb); sb.append("!"); System.out.println(sb); sb.append('?'); System.out.println(sb); sb.reverse(); System.out.println(sb); sb.reverse(); System.out.println(sb); sb.delete(0, 4); System.out.println(sb); sb.delete(4); System.out.println(sb); } catch (IndexIsNagetiveException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IndexIsOutofRangeException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }


HOW2J公众号,关注后实时获知布最新的教程和优惠活动,谢谢。


问答区域    
2018-10-09 作业
asd32123



作业
public class MyStringBuffer {
	int capacity = 16;
    int length = 0;
    char[] value;
    public MyStringBuffer(){
        value = new char[capacity];
    }
     
    //有参构造方法
    public MyStringBuffer(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 insert(int pos, char b) throws Exception {
        insert(pos,String.valueOf(b));
    }
 

    public void delete(int start) throws Exception {
         
        delete(start,length);
    }
  
    public int length() {
        // TODO Auto-generated method stub
        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 s) {
			super (s);
		}
	}
	
	public void delete(int start, int end) throws Exception{
        //边界条件判断
        if(start<0) {
        	throw new IndexIsNagetiveException("下标为负异常");
        }
         
        if(start>length) {
        	throw new IndexIsOutofRangeException("下标超出范围异常");
        }
         
        if(end<0) {
        	throw new IndexIsNagetiveException("下标为负异常");
        }
         
        if(end>length) {
        	throw new IndexIsOutofRangeException("下标超出范围异常");
        }
         
        if(start>=end) {
        	throw new IndexIsOutofRangeException("下标超出范围异常");
        }
         
        System.arraycopy(value, end, value, start, length- end);
        length-=end-start;
         
    }
	
	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.5f);
            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 static void main(String[] args) {
		MyStringBuffer sb = new MyStringBuffer("there ligtht");
		System.out.println(sb);
        try {
			sb.insert(-4, "let ");
		} catch (Exception e) {
			System.out.println("异常的具体原因:"+e.getMessage());
			e.printStackTrace();
		}
        System.out.println(sb);
        try {
			sb.delete(0,44);
		} catch (Exception e) {
			System.out.println("异常的具体原因:"+e.getMessage());
			e.printStackTrace();
		}
        System.out.println(sb);
        
	}
}

							






答案 或者 代码至少填写一项, 如果是自己有问题,请重新提问,否则站长有可能看不到





2018-09-02 按在地上摩擦~
脑子转不过来



作业~
public class IndexIsNagetiveException extends Exception{

}
------------------------------------------------------------------------------------------------------
public class IndexIsOutofRangeException extends Exception {

}
------------------------------------------------------------------------------------------------------
public interface IStringBuffer {
	public void append(String str) throws IndexIsOutofRangeException, IndexIsNagetiveException; // 追加字符串

	public void append(char c) throws IndexIsOutofRangeException, IndexIsNagetiveException; // 追加字符

	public void insert(int pos, String b) throws IndexIsOutofRangeException, IndexIsNagetiveException; // 指定位置插入字符串

	public void insert(int pos, char b) throws IndexIsOutofRangeException, IndexIsNagetiveException; // 指定位置插入字符

	public void delete(int start) throws IndexIsOutofRangeException, IndexIsNagetiveException; // 从开始位置删除剩下的

	public void delete(int start, int end) throws IndexIsOutofRangeException, IndexIsNagetiveException; // 从开始位置删除结束位置

	public void reverse(); // 反转

	public int length(); // 返回长度
}

------------------------------------------------------------------------------------------------------
/**
 * value:用于存放字符数组
 * capacity: 容量
 * 无参构造方法:根据容量初始化value
 */
public class MyStringBuffer implements IStringBuffer {
	int capacity = 16;		//容量
	int length = 0;			//长度
	char[] value;			//用于存放字符数组
	
	public MyStringBuffer() {
		value = new char[capacity];	
	}
	
	public MyStringBuffer(String str) {
		this();
		if(str == null)
			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();
	}
	
	@Override
	public void append(String str) throws IndexIsNagetiveException,IndexIsOutofRangeException {
		insert(length,str);
	}

	@Override
	public void append(char c) throws IndexIsNagetiveException,IndexIsOutofRangeException {
		append(String.valueOf(c));
	}

	@Override
	public void insert(int pos, String b) throws IndexIsNagetiveException,IndexIsOutofRangeException{
		//边界判断
		if(pos < 0) return;	
		if(pos > length) return;
		if(b == null) return;
		
		//扩容
		while(length + b.length() > capacity) {
			capacity = (int)((length + b.length())*1.5f);
			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;
	}

	@Override
	public void insert(int pos, char b) throws IndexIsNagetiveException,IndexIsOutofRangeException {
	
	}

	@Override
	public void delete(int start) throws IndexIsNagetiveException,IndexIsOutofRangeException {
		delete(start,length);
	}

	@Override
	public void delete(int start, int end) throws IndexIsNagetiveException,IndexIsOutofRangeException {
		//边界判断
		if(start < 0) return;
		if(start > length) return;
		if(end < 0) return;
		if(end > length) return;
		if(start == end) return;
		
		System.arraycopy(value, end, value, start, length -end);
		length -= end - start;
	}

	@Override
	public void reverse() {
		for (int i = 0; i < length / 2; i++) {				//假设length为4   长度4/2 = 2 value="word"
			char temp = value[i];							// temp = value[0](w)
			value[i] = value[length - i -1];				// value[0] = value[4 - 0 - 1(3)](d)
			value[length - i - 1] = temp;					// value[3](d) = value[0](w)
		}
	}

	@Override
	public int length() {
		return length;
	}
	
	public String toString() {
		char[] realValue = new char[length];
		System.arraycopy(value, 0, realValue, 0, length);
		return new String(realValue);
	}
	
	public static void main(String[] args) {
		MyStringBuffer sb = new MyStringBuffer("there light");
		try {
			sb.delete(1,3);
		} catch (IndexIsNagetiveException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IndexIsOutofRangeException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(sb);
	}
}
------------------------------------------------------------------------------------------------------

							


1 个答案

graceL 答案时间:2018-09-25




答案 或者 代码至少填写一项, 如果是自己有问题,请重新提问,否则站长有可能看不到





2018-05-29 还是关于带参构造方法中 传string类型参数 调用父类构造方法的疑惑
2018-05-29 带参的构造方法,并调用父类的对应的构造方法
2018-05-05 请问e.getMessage()这个方法从哪儿来的
2018-04-19 append内部做try, catch
2018-03-24 交作业
2018-01-18 视频播放问题……
2018-01-14 我的自定义Exception为什么不能是public? 而去掉后就好了,why?
2018-01-14 站长打错了个英文单词。。Negative
2017-12-23 继承中, this指向问题。。。
2017-11-14 无法自定义异常
2017-11-13 请问throw和throws是结合起来用的吗?
2017-09-10 站长,EnemyHeroIsDeadException的无参构造方法有什么用呢?
2017-08-10 如果英雄name的定义是public类型的,那为什么还要定义toString()方法呢?
2017-08-08 练习题
2017-07-14 子类可以访问父类的私有变量吗
2017-05-15 super(msg)中的super指的就是exception这一个父类吗?这是调用的exception的有参构造方法?
2017-03-26 为什么要把msg传给父类呢
2017-03-21 我比较笨,还望站长说的详细一些
2017-02-10 提问测试
2016-12-07 还是不太清楚capacity,length和value这三个分别什么意思
2016-09-30 Nagetive拼错了




提问之前请登陆
关于 JAVA 中级-异常处理-自定义异常 的提问

尽量提供截图代码异常信息,有助于分析和解决问题。 也可进本站QQ群交流: 902680467
提问尽量提供完整的代码,环境描述,越是有利于问题的重现,您的问题越能更快得到解答。
对教程中代码有疑问,请提供是哪个步骤,哪一行有疑问,这样便于快速定位问题,提高问题得到解答的速度
在已经存在的几千个提问里,有相当大的比例,是因为使用了和站长不同版本的开发环境导致的,比如 jdk, eclpise, idea, mysql,tomcat 等等软件的版本不一致。
请使用和站长一样的版本,可以节约自己大量的学习时间。 站长把教学中用的软件版本整理了,都统一放在了这里, 方便大家下载: http://how2j.cn/k/helloworld/helloworld-version/1718.html

上传截图