码迷,mamicode.com
首页 > 其他好文 > 详细

抛出异常

时间:2020-02-09 20:34:47      阅读:67      评论:0      收藏:0      [点我收藏+]

标签:out   内容   ini   方法   str   catch   star   结果   输出   

更新记录

【1】2020.02.09-18:15

1.完善内容

正文

我们去学习Java的异常处理的时候,肯定写过抛出异常的方法
但是如果你将代码改成这个样子:

public class exception {
    public static void test() throws ClassCastException{
        int[] arr = new int[-3];
    }
    public static void main(String[] args) {
        int a = 3, b = 0;
        System.out.println("start");
        try {
            test();
        }
        catch(ClassCastException cce) {
            cce.printStackTrace(System.out);
        }
        catch(Exception e) {
            e.printStackTrace(System.out);
        }
        System.out.println("finish");
    }
}

上面的实例中test本应该抛出NegativeArraySizeException异常
然而我们将它改为了ClassCastException
那运行结果怎么样呢?

start
java.lang.NegativeArraySizeException
    at exception.test(exception.java:3)
    at exception.main(exception.java:9)
finish

从上面的运行结果中,我们可以看出,catch代码块依然正常的接收到了异常信息
那能不能说明catch(ClassCastException cce)与throws ClassCastException正常运作只不过是printStackTrace(System.out)的内容改变了呢?
别急着下结论,先再改改代码观察一下结果
这一次,我们删除catch(Exception e)

public class exception {
    public static void test() throws ClassCastException{
        int[] arr = new int[-3];
    }
    public static void main(String[] args) {
        int a = 3, b = 0;
        System.out.println("start");
        try {
            test();
        }
        catch(ClassCastException cce) {
            cce.printStackTrace(System.out);
        }
        System.out.println("finish");
    }
}

以下是运行结果:

start
Exception in thread "main" java.lang.NegativeArraySizeException
    at exception.test(exception.java:3)
    at exception.main(exception.java:9)

结果怎么样?finish没有被输出,也就是说NegativeArraySizeException异常没有被接收到
所以我们可以看出:throws ClassCastException并不是意味着这个类抛出的异常全是ClassCastException异常
也有可能是别的。

另外,直接自定义名称是不可以的,像

public static void test() throws LalalaException{
    int[] arr = new int[-3];
}

直接写是不行的,必须实现LalalaException类。

抛出异常

标签:out   内容   ini   方法   str   catch   star   结果   输出   

原文地址:https://www.cnblogs.com/zythonc/p/12287997.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!