Java中的异常处理与抛出

一、异常处理

程序运行过程中出现的,导致程序无法继续运行的错误叫做异常。

Java中有多种异常,所有异常的父类是Throwable,他主要有两个子类Error和Exception。

Error一般是JVM出现问题,不用处理,也无法处理。

Exception下有多个子类,但主要分为两种。一种是RuntimeException,这种异常可以处理也可以不处理

另一种是非RuntimeException,这种异常必须处理。

常见的RuntimeException:

1、NullPointerException   (空指针异常)

2、IndexOutOfBoundsException  (数组下标越界异常)

3、NumberFormatException  (数据格式异常)

4、ClassCastException     (类型转换异常)

5、IllegalArgumentException    (非法参数异常)

6、ArithmeticException      (算数异常)

7、IllegalStateException    (非法语句异常)

这里列举两个例子:

 NullPointerException 示例:

package None6;

public class Test {
    int a;
    public int show() {
        return 0;
    }
}


package None6;

public class TestIt {
    //仅声明test,并未创建对象
    Test test;
    test.show();
}

这里test仅声明并未实际指向某个对象,空指针无法调用不属于他的方法,所以在后一条代码实际调用show()方法时会报空指针异常。

IndexOutOfBoundsException 示例:

package None6;

public class TestIt {
    public static void main(String[] args) {
        int[] a = new int[3];
        a[0] = 0;
        a[1] = 1;
        a[2] = 2;
        a[3] = 3;
    }

}

这里ArrayIndexOutOfBoundsException异常是IndexOutOfBoundsException异常的子类。

需要处理的异常可用try catch来处理:

package None7;

public class math {

    public static int add(String a,String b) {
        int sum = Integer.parseInt(a);
        sum+=Integer.parseInt(b);
        return sum;
    }
}

package None7;

public class testit {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.err.println(math.add("100", "100"));
    }

}

例如本示例中,当add()方法中的参数为数字时不会出现异常,但当参数中出现字母之类的字符时可能会抛出异常

 

处理办法;

package None7;

public class math {

    public static int add(String a,String b) {
        try {
            int sum = Integer.parseInt(a);
            sum+=Integer.parseInt(b);
            return sum;
        } catch (Exception e) {
            // TODO: handle exception
            //打印出错信息
            System.err.println(e.getMessage());
        }
        finally{
            System.err.println("结束!");
        }
        return 0;
    }
}

package None7;

public class testit {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.err.println(math.add("100a", "100"));
    }

}

结果为:

二、抛出异常

上面讲了,非RuntimeException异常必须处理,而我们当时如果不知道怎处理或者暂时不想处理时可用throw向上一级一级抛出,最终会抛给虚拟机处理。

示例:

结果:

这个例子中动态加载类123时,因为123类不存在所以会报错,然后将用throw将这个错误抛出。

这个错误首先抛出给主函数入口,然后再抛出给虚拟机。

如有错误,希望大家能指正,感谢!

努力努力再努力!

猜你喜欢

转载自www.cnblogs.com/lemonxu/p/10349519.html