gpt4 book ai didi

java - 关于最终重抛

转载 作者:搜寻专家 更新时间:2023-11-01 02:06:45 24 4
gpt4 key购买 nike

我在 Precise Rethrow 的文档中读到,http://www.theserverside.com/tutorial/OCPJP-Use-more-precise-rethrow-in-exceptions-Objective-Java-7

Basically, you can list specific exceptions in the throws clause of your method, even if they are not explicitly handled by a catch block if:

The try block actually throws that specific exception at some point in time.

The specific Exception isn't already handled at any point by a preceding catch block

The exception named in the throws clause of the method signature must be on the class hierarchy of at least one exception being handled and rethrown by a catch block (subtype or supertype)

看一下代码(注意main的throws子句)

class OpenException extends Exception {}

class CloseException extends Exception {}

public class PRethrow
{
public static void main(String args[]) throws OpenException, CloseException, java.io.IOException
{
boolean flag = true;
try
{
if (flag)
{
throw new OpenException();
}
else
{
throw new CloseException();
}
}
catch (Exception e)
{
System.out.println(e.getMessage());
throw e;
}
}
}

第一个条件中明确提到,如果 try block 在某个时间点实际抛出特定异常,则可以在 throws 子句中列出特定异常。

在我的代码中,try block 从不抛出 java.io.IOException,但仍将其包含在 throws 子句中不会产生任何错误。

为什么?

最佳答案

您提到的引用具有误导性:

  • 如果在您的方法体中可能抛出检查异常,您必须在方法的 throws 子句中声明它。
  • 但是您可以将任何异常添加到方法的throws 子句中,无论它是否真的可以被抛出。

例如这个编译:

public void m() throws IOException {}

关于java - 关于最终重抛,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30925951/

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