throws 除了传播一个 checked Exception 之外还有其他作用吗?

Is there any other role of throws instead of propagating a checked Exception?

在研究了越来越多关于 Exception Handling 中的 throws 语句后,我发现 confused.I -

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");
    }
}

没有使用 throws,仍然有一个异常 - 我的控制台显示以下错误 -

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)

直到我没有将 meth1 的调用放在 try-catch 块中,尽管使用了 throws 还是出现了异常。这里throws的作用是什么?

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

我需要你在 it.I 上午确认 confused.My 一行查询是 -

除了传播一个CheckedExceptionthrows还有其他作用吗?

我认为异常处理是非常合乎逻辑的,throws 是必要的,因为你并不总是希望在它可能发生的级别上处理异常。

假设您有一个管理存在于多个文件中的值的对象

public class MultipleFileManager {
    private List<String> filesContent;
    .
    . 
    .
    public void addFileContent(String filename) {
        File file = new File(filename);
        try {
            FileReader fr = new FileReader(file);
            .
            //adding filecontent to filesContent list
            .
        } catch (IOException e) {
            System.err.println("file not added");
        }
    }
}

在此示例中,您显然希望在 MultipleFileManager 级别处理异常,因为如果仅 一个损坏的文件可能使整个线程

Therefore throws IOException statement in the FileReader class methods 告诉你要么你将在级别处理异常addFileContent() 级别,否则如果遇到损坏的文件,您可能会导致整个线程崩溃并抛出异常。

如果碰巧这个线程是主线程,整个应用程序将崩溃。

如你所说,有2种例外。

  • "Checked exceptions" 需要开发人员的注意。 当您使用抛出检查异常的方法时(即 IOException) ,您需要处理它(即捕获它)或传播它给调用者(即抛出它)假设调用者会捕获它。

  • "Unchecked exceptions"不需要特别注意。这些都是异常,比如NullPointerException,bug。 您不想编写代码来掩盖潜在的错误。不可能面面俱到。不过,如果你想捕获一个未经检查的异常,你可以。

  • 注意:还有一些其他可抛出的对象。您可以抛出扩展 Throwable class 的所有对象。但是你不应该在你的代码中使用这个功能。这实际上是针对系统错误和断言。

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

编译器对此进行检查。它很容易识别未经检查的异常,因为未经检查的异常扩展了 RuntimeException class.

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

让我们诊断:

首先你的程序会因为代码

而抛出异常
throw new IOException();

当你放置一个 try catch 块时,异常将在 catch 块中处理。

记住有两种类型的异常:已检查和未检查的异常,然后是错误

throw关键字只是引发异常(也可以是自定义异常!!!)并停止执行(如果没有使用catch来处理异常)

一般做法:

  • catch 块将处理异常
  • Throws 会将错误传递给调用者,没有恢复机制。