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-04-19 append内部做try, catch
hive
append的两个方法,为什么不在内部做try catch处理掉?append原理上来讲不是永远不会出现自定义的异常吗?内部处理会不会更说得通一点....








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




2018-03-24 交作业
夜神1997



交作业
package digit;

public interface IStringBuffer {

	public void append(String str) throws Exception; //追加字符串
    public void append(char c) throws Exception;  //追加字符
    public void insert(int pos,char b) throws Exception;//指定位置插入字符
    public void insert(int pos,String b) throws Exception; //指定位置插入字符串
    public void delete(int start) throws Exception; //从开始位置删除剩下的
    public void delete(int start,int end) throws Exception; //从开始位置删除结束位置-1
    public void reverse(); //反转
    public int length(); //返回长度
}
///////////////////////////////////////////////////////////////////////////////////////
package digit;

import java.util.Date;

public class MyStringBuffer implements IStringBuffer{

	char[] value;
	int length = 0;
	int capacity = 16;
	
	public MyStringBuffer(){
		value = new char[capacity];
	}
	
	public MyStringBuffer(String str){
		this();
		
		if(str == null)
			return;
		
		if(capacity < str.length()){
			capacity = str.length()*2;
			value = new char[capacity];
		}
		
		char[] c = str.toCharArray();
		System.arraycopy(c,0,value,0,str.length());
		length = str.length();
	}
	
	@Override
	public void append(String str) throws indexlsNagetiveException,indexlsOutofRangeException,NullPointerException{
		this.insert(length,str);
	}
	
	@Override
	public void append(char c) throws indexlsNagetiveException,indexlsOutofRangeException,NullPointerException{
		this.append(String.valueOf(c));
	}
	
	@Override
    public void insert(int pos,char b) throws indexlsNagetiveException,indexlsOutofRangeException,NullPointerException{
    	this.insert(pos,String.valueOf(b));
    }
	
	@Override
    public void insert(int pos,String b) throws indexlsNagetiveException,indexlsOutofRangeException,NullPointerException{
    	if(b == null)
    		throw new NullPointerException("插入为null");
    	
    	if(pos < 0)
    		throw new indexlsNagetiveException("小于边界");
    	
    	if(pos > length)
    		throw new indexlsOutofRangeException("大于边界");
    	
    	if(capacity < length + b.length()){
    		capacity = (int)((length + b.length()) * 1.5);
    		
    		char[] c = new char[capacity];
    		System.arraycopy(value, 0, c, 0, length);
    		value = c;
    	}
    	
    	System.arraycopy(value, pos, value, pos + b.length(), length - pos);
    	System.arraycopy(b.toCharArray(), 0, value, pos, b.length());
    	
    	length = length + b.length();
    }
	
	@Override
    public void delete(int start) throws indexlsNagetiveException,indexlsOutofRangeException{
    	this.delete(start,length);
    }
	
	@Override
    public void delete(int start,int end) throws indexlsNagetiveException,indexlsOutofRangeException{
    	if(start < 0 || end < 0){
    		throw new indexlsNagetiveException("小于边界");
    		//return;
    		}
    	
    	if(start >= end || start > length || end > length){
    		throw new indexlsOutofRangeException("超出边界");
    		//return;
    		}
    	
    	System.arraycopy(value, end, value, start, length - end);
    	
    	length -= end - start;
    }
	
	@Override
    public void reverse(){
    	for(int i = 0; i < length/2; i++){
    		char tmp = value[i];
    		value[i] = value[length-1-i];
    		value[length-1-i] = tmp;
    	}
    }
	
	@Override
    public int length(){
    	return length;
    }
	
	public String toString(){
		char[] str = new char[length];
		System.arraycopy(value, 0, str, 0, length);
		return new String(str);
	}
	
	class indexlsNagetiveException extends Exception{
		
		public indexlsNagetiveException(){
			
		}
		public indexlsNagetiveException(String msg){
			super(msg);
		}
	}
	
	class indexlsOutofRangeException extends Exception{
		
		public indexlsOutofRangeException(){
			
		}
		public indexlsOutofRangeException(String msg){
			super(msg);
		}
	}
	
	class NullPointerException extends Exception{
		
		public NullPointerException(){
			
		}
		public NullPointerException(String msg){
			super(msg);
		}
	}
	
	public static void main(String[] args){
		
		/*
		int len = 1000000;
		String[] str = new String[len];
		StringBuffer sb = new StringBuffer();
		
		short start = '0';
		short end = 'z'+1;
		
		for(int i = 0; i < len; i++){
			for(int j = 0; j < 10; j++){
				while(true){
					char c = (char)(Math.random()*(end - start)+start);
					if(Character.isLetterOrDigit(c)){
						sb.append(c);
						break;
					}
				}
			}
			str[i] = sb.toString();
			sb.delete(0, sb.length());
		}
		
		StringBuffer sb1 = new StringBuffer();
		MyStringBuffer msb = new MyStringBuffer();
		
		long t1 = new Date().getTime();
		for(int i = 0; i < len; i++){
			sb1.append(str[i]);
		}
		long tsb = new Date().getTime() - t1;
		System.out.printf("用系统Stringbuffer输出耗时%d毫秒%n",tsb);
		
		long t2 = new Date().getTime();
		for(int i = 0; i < len; i++){
			msb.append(str[i]);
		}
		long tmsb = new Date().getTime() - t2;
		System.out.format("用自建MyStringBuffer输出耗时%d毫秒",tmsb);
		*/
		
		MyStringBuffer msb = new MyStringBuffer();
		int start = 0;
		int end = msb.toString().length();
		String str = "String";
		char c = 'c';
		
		try{
			msb.append(c);
			msb.append(str);
			msb.delete(start);
			msb.insert(start,c );
			msb.insert(start, str);
			
			end = msb.toString().length();
			msb.delete(start,end);
		}
		catch(Exception e){
			if(e instanceof indexlsNagetiveException)
				System.out.println("异常类型为:"+e.getMessage());
			if(e instanceof indexlsOutofRangeException)
				System.out.println("异常类型为:"+e.getMessage());
			if(e instanceof NullPointerException)
				System.out.println("异常类型为:"+e.getMessage());
			
			e.printStackTrace();
		}
		
	}
}

							






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





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群交流: 389538688
站长会在每个工作日早上尽量回答提问(如果有漏掉没有回答的,请进群提醒一下)
提问尽量提供完整的代码,环境描述,越是有利于问题的重现,您的问题越能更快得到解答。
对教程中代码有疑问,请提供是哪个步骤,哪一行有疑问,这样便于快速定位问题,提高问题得到解答的速度
站长是玻璃心,提问的时候请语气温柔些 kiss~
截止2017-5-19日累计提问 1638个,站长回答了 1546个
截止2017-8-15日累计提问 2788个,站长回答了 2544个

上传截图