public int method(int[] arr ,int index)throws FuShuIndexException //定义一个函数method方法 并返回。进行声明抛出
{
if(index<0)
throw new FuShuIndexException();//建对象进行抛出
return arr[index];
}
}
class ExceptionDemo
{
public static void main(String[] args)
{
int [] arr= new int[3];
Demo d = new Demo();
try
{
int num = d.method(arr,-3);//被检测的代码
System.out.println("num"+num);
}
catch (FuShuIndexException f)//接受异常对象
{
System.out.println(f.getMessage());//处理异常代码
f.printStackTrace();
}
System.out.println("over");
}
}
运行结果为:FuShuIndexException: 角标为负
at Demo.method(ExceptionDemo.java:17)
at ExceptionDemo.main(ExceptionDemo.java:30)
over
总结:
(1)catch里的处理f.getMessage(),f.printStackTrace()能调用时因为继承,getMessage():输出异常的信息;printStackTrace():输出导致异常的详细信息,这是父类Exception有的直接拿来用的。
(2)捕捉后可以继续运行程序并没有终止。
(3)能解决的catch不能的throw作者: LGQ 时间: 2015-7-21 21:14
不错呦:)