----------------------------------
测试
package TestException;
public class TestFinally {
public static void main(String[] args) {
Test s = new Test();
try {
s.show(3);
} catch (ItCantbeNegative e) {
System.out.println(e.getMessage());
}catch(ArrayIndexOutOfBoundsException e){
System.out.println(e.getMessage());
}
s.s();
}
}
class Test{
public int show(int index) throws ArrayIndexOutOfBoundsException,ItCantbeNegative{
int[] a = new int[3];
if(index<0)
//必须在ItCantbeNegative 中增加字符串构造函数,并调用父类的构造函数处理,不然无法捕获到这个字符串提示
throw new ItCantbeNegative("数组不能为负数"+index+"数组最长为:0-"+a.length);
if(index>a.length-1)
throw new ArrayIndexOutOfBoundsException("数组越界"+index+"数组最长为"+(a.length-1));
return a[index];
}
public void s(){
}
}
----------------
自定义异常类
package TestException;
public class ItCantbeNegative extends RuntimeException{
ItCantbeNegative(){
super();
}
//这里须写 super(e);去调用父类的Stiring类型的构造函数,从而获取到抛出的异常字符串
ItCantbeNegative(String e){
super(e);
}
}