gpt4 book ai didi

java - 多次抛出的异常是检查的还是运行时的?

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:43:34 26 4
gpt4 key购买 nike

我有一个异常链,其中 method1method2 抛出异常,method2main 抛出异常。由于某种原因,编译器强制我处理 method2 中的错误,如果我不这样做,则将其标记为错误,表明这是一个已检查的异常。但是当相同的 Exception 被进一步抛出到 main 时,编译器允许我忽略它并且不显示任何错误。

method1中原来的Exception是一个ParseException,检查过了。但是该方法在 header 中有一个通用的 throws Exception 子句,并且将同一对象抛出到 method2,后者具有相同的 throws Exception 子句。该Exception何时以及如何失去被编译器检查/捕获的状态?

编辑澄清:

public void method1() throws Exception{
// code that may generate ParseException
}

public void method2() throws Exception{
method1(); //compiler error (if the throws clause is left out)
}

public static void main(String[] args){
method2(); //ignored by compiler, even though the exception isn't caught or thrown or handled at all
}

编辑:对不起大家,这个问题是基于一个错误... main 方法实际上有一个我遗漏的 throws Exception 子句。我已经删除了它,代码现在按预期运行。感谢所有的帮助!

最佳答案

异常是否被检查完全取决于它是什么类型的异常:如果是RuntimeException 或其子类,则不检查;否则,它是。 (是的,RuntimeExceptionException 的子类——Java 库设计的失败之一,但不是最主要的。)

编译器检查的是方法签名。所以抛出的实际异常是无关紧要的(为此目的)。如果方法说 throws Exception 那么你必须在你的方法中捕获 Exception 或者声明方法 throws Exception。方法应始终使用最窄的可能 throws 子句——例如,not throws Exceptionthrows ParseException.

(我说“不相关(为了这个目的)”是因为,当然,编译器将做的其他事情之一是检查您是否抛出未涵盖的已检查异常通过你的 throws 子句。)

编辑 您在编辑中添加的代码将无法编译:1. 它在没有实例的情况下调用实例方法,并且 2. main 需要声明它抛出 Exception

这段代码解决了其他问题,并且(正确地)证明了 main 需要 throws Exception 子句:

public class CheckTest
{
public static final void main(String[] params)
{
new CheckTest().method2();
}

public void method1() throws Exception{
throw new java.text.ParseException("foo", 2);
}

public void method2() throws Exception{
this.method1();
}
}

结果:

CheckTest.java:27: unreported exception java.lang.Exception; must be caught or declared to be thrown

new CheckTest().method2();
^
1 error

关于java - 多次抛出的异常是检查的还是运行时的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2781845/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com