gpt4 book ai didi

java - 处理已检查的异常

转载 作者:搜寻专家 更新时间:2023-11-01 01:57:08 25 4
gpt4 key购买 nike

我正在阅读“A programmer guide to Java SCJP certificate”一书中的异常处理。作者写道:

If a checked exception is thrown in a method, it must be handled in one of three ways:

1.By using a try block and catching the exception in a handler and dealing with it

2.By using a try block and catching the exception in a handler, but throwing another exception that is either unchecked or declared in its throws clause

3.By explicitly allowing propagation of the exception to its caller by declaring it in the throws clause of its method header

第一个和第三个我看的很清楚,但是第二个让我很困惑。我担心的是:

-即使我不抛出任何其他未经检查的异常也没有问题,那么为什么我们必须在这里抛出另一个异常?

-为什么我们必须在 throws 子句中重新声明我们捕获的异常?我认为处理程序已经结束了。

谢谢大家。

最佳答案

这本书只列出了三个允许的选项。

-It's still alright even if I don't throw any other unchecked exceptions, so why do we have to throw another exception at here?

您可能想抛出另一个更具描述性的异常,例如添加更多信息。

-Why do we have to re-declare the exception that we have caught, in throws clause? I think it's over by the handler.

您不必重新申报。但是如果你抛出的新异常被检查,那么你必须在 throws 子句中声明它。事实上,您刚刚捕获的异常即使被检查也不需要声明。

关于java - 处理已检查的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6319525/

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