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

在越来越多地研究异常处理中的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("111111111111");
    }
}
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将只打印它.

相关文章

Java中的String是不可变对象 在面向对象及函数编程语言中,不...
String, StringBuffer 和 StringBuilder 可变性 String不可变...
序列化:把对象转换为字节序列的过程称为对象的序列化. 反序...
先说结论,是对象!可以继续往下看 数组是不是对象 什么是对...
为什么浮点数 float 或 double 运算的时候会有精度丢失的风险...
面试题引入 这里引申出一个经典问题,看下面代码 Integer a ...