加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 是否有任何其他的throws角色而不是传播已检查的Exceptio

发布时间:2020-12-15 04:27:20 所属栏目:Java 来源:网络整理
导读:在越来越多地研究异常处理中的throws语句后,我感到困惑.我发现 – If a method is capable of causing an exception that it does not handle,it must specify this behavior so that callers of the method can guard themselves against that exception. c
在越来越多地研究异常处理中的throws语句后,我感到困惑.我发现 –

If a method is capable of causing an exception that it does not
handle,it must specify this behavior so that callers of the method
can guard themselves against that exception.

class Boxing1{  
public static void main(String args[]) throws IOException{
    new B().meth2();
    System.out.println("33333333");
}
}
class A{

    void meth1() throws IOException{
        throw new IOException();
        //throw new NullPointerException();
        //System.out.println("222222222211");
    }
}
class B{
    void meth2() throws IOException{
        new A().meth1();
        System.out.println("2222222");
    }
}

而不是使用抛出仍有一个例外 – 我的控制台显示以下错误 –

Exception in thread "main" java.io.IOException
    at A.meth1(Boxing1.java:17)
    at B.meth2(Boxing1.java:24)
    at Boxing1.main(Boxing1.java:10)

直到我没有在try-catch块中调用meth1,尽管使用了throws,但是有一个异常.抛出的角色是什么?

try{new A().meth1();}catch(Exception e){System.out.println(e);}

我需要你的确认.我很困惑.我的一行查询是 –

抛出还有其他任何角色而不是传播CheckedException吗?

解决方法

如你所说,有两种例外.

>“检查异常”需要开发人员的注意.当您使用抛出已检查异常(即IOException)的方法时,您需要处理它(即捕获它)或将其传播给调用者(即抛出它),假设调用者将捕获它.
>“未经检查的例外”不需要特别注意.这些是NullPointerException,bug等异常.您不希望编写代码来涵盖潜在的错误.无法涵盖一切.不过,如果你想捕获一个未经检查的异常,你可以.
>注意:还有一些其他可抛物体.您可以抛出扩展Throwable类的所有对象.但是您不应该在代码中使用此功能.这实际上是系统错误和断言.

如果抛出一个已检查的异常,则需要通过在方法签名中指定抛出SomeException来警告开发人员.对于未经检查的例外,您不需要.

编译器检查这个.它可以轻松识别未经检查的异常,因为未经检查的异常会扩展RuntimeException类.

最后,在您的情况下,您将异常一直传播到top()方法.甚至在那里你继续传播它.在这种情况下,JVM将只打印它.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读