异常----自定义异常

来源:互联网 发布:python查找txt内容 编辑:程序博客网 时间:2024/06/17 15:15
/* 对于角标是整数不存在,可以用角标越界来表示。 对于是负数的情况,我们不乐意用越界来表示, 而负数角标这种异常在java中并没有定义过。 那么就按照java异常的创建思想,面向对象,将负数角标进行自定义描述。并封装成对象。 这种自定义的问题描述成为自定义异常。 注意:如果让一个类继承异常类,必须要继承异常体系,因为只有成为异常体系的子类才有资格具备可抛型。    才可以被两个关键字操作:throw throws */class FuShuIndexException extends Exception{    FuShuIndexException()    {}    FuShuIndexException(String msg)    {        super(msg);    }}class Demo{    public void method(int[] arr,int index) throws FuShuIndexException//进行声明    {        if(arr == null)        {            throw new NullPointerException("数组的引用不能为空!");        }        if(index >= arr.length)        {            throw new ArrayIndexOutOfBoundsException("数组的角标越界了,兄弟。"+index);        }        if(index < 0)        {            throw new FuShuIndexException("角标变成负数啦");            //报错 未报告的异常,必须对其进行捕捉或声明以便抛出。        }        System.out.println(arr[index]);     }}public class ExceptionDemo2 {    public static void main(String[] args) throws FuShuIndexException{//进行声明        int[] arr = new int [3];        new Demo().method(arr,-3);      }}
原创粉丝点击