抛出或尝试捕获

发布于 2024-09-09 03:07:32 字数 221 浏览 7 评论 0原文

在决定是否向方法添加 throws 子句或使用 try-catch 时,一般经验法则是什么?

根据我自己的阅读,当调用者破坏了契约的末尾(传递的对象)时,应该使用throws,并且当在方法内部执行的操作期间发生异常。这是正确的吗?如果是这样,调用方应该做什么?

PS:通过谷歌和SO搜索,但希望对此有一个明确的答案。

What is the general rule of thumb when deciding whether to add a throws clause to a method or using a try-catch?

From what I've read myself, the throws should be used when the caller has broken their end of the contract (passed object) and the try-catch should be used when an exception takes place during an operation that is being carried out inside the method. Is this correct? If so, what should be done on the callers side?

P.S: Searched through Google and SO but would like a clear answer on this one.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

一抹微笑 2024-09-16 03:07:33

如果引发异常的方法有足够的信息来处理它,那么它应该捕获并生成有关发生了什么以及正在处理哪些数据的有用信息。

If the method where the exception got raised has a sufficent amount of information to deal with it then it should catch, generate useful information about what happened and what data was being processed.

我家小可爱 2024-09-16 03:07:33

如果方法可以对对象的状态、传递给该方法的任何参数以及该方法所作用的任何其他对象做出合理的保证,则该方法应该仅抛出异常。例如,如果预期存在于集合中的项目不存在,则应该从集合中检索调用者期望包含在其中的项目的方法可能会抛出检查异常。 。捕获该异常的调用者应该期望该集合不包含有问题的项目。

请注意,虽然 Java 允许通过声明为抛出适当类型异常的方法来冒泡检查异常,但这种用法通常应被视为反模式。例如,想象一下某个方法 LookAtSky() 被声明为调用 FullMoonException,并预计在月球满时抛出它;进一步想象一下,LookAtSky() 调用 ExamineJupiter(),它也被声明为 throws FullMoonException。如果 ExamineJupiter() 抛出 FullMoonException,并且 LookAtSky() 没有捕获它并处理它或将其包装在某些其他异常类型,名为 LookAtSky 的代码会假设该异常是地球月球满月的结果;它不知道木星的一颗卫星可能是罪魁祸首。

调用者可能期望处理的异常(基本上包括所有已检查的异常)只有在异常对于方法的调用者和被调用的方法意味着相同的情况时才应该允许通过方法渗透。如果代码调用一个被声明为抛出某些检查异常的方法,但调用者并不期望它在实践中抛出该异常(例如,因为它认为它预先验证了方法参数),则应该捕获并包装检查异常在某些未经检查的异常类型中。如果调用者不期望抛出异常,则调用者不能期望它具有任何特定含义。

A method should only throws an exception if it can make reasonable guarantees surrounding the state of the object, any parameters passed to the method, and any other objects the method acts upon. For example, a method which is supposed to retrieve from a collection an item which the caller expects to be contained therein might throws a checked exception if the item which was expected to exist in the collection, doesn't. A caller which catches that exception should expect that the collection does not contain the item in question.

Note that while Java will allow checked exceptions to bubble up through a method which is declared as throwing exceptions of the appropriate types, such usage should generally be considered an anti-pattern. Imagine, for example, that some method LookAtSky() is declared as calling FullMoonException, and is expected to throw it when the Moon is full; imagine further, that LookAtSky() calls ExamineJupiter(), which is also declared as throws FullMoonException. If a FullMoonException were thrown by ExamineJupiter(), and if LookAtSky() didn't catch it and either handle it or wrap it in some other exception type, the code which called LookAtSky would assume the exception was a result of Earth's moon being full; it would have no clue that one of Jupiter's moons might be the culprit.

Exceptions which a caller may expect to handle (including essentially all checked exceptions) should only be allowed to percolate up through a method if the exception will mean the same thing to the method's caller as it meant to the called method. If code calls a method which is declared as throwing some checked exception, but the caller isn't expecting it to ever throw that exception in practice (e.g. because it thinks it pre-validated method arguments), the checked exception should be caught and wrapped in some unchecked exception type. If the caller isn't expecting the exception to be thrown, the caller can't be expecting it to have any particular meaning.

翻了热茶 2024-09-16 03:07:33

什么时候用什么。我对此进行了很多搜索。
没有硬性规定。

“但是作为开发人员,受检查的异常必须包含在方法的 throws 子句中。这对于编译器知道要检查哪些异常是必要的。
按照惯例,未经检查的异常不应包含在 throws 子句中。
包含它们被认为是糟糕的编程实践。编译器将它们视为注释,并且不检查它们。”

来源:Kathy Sierra 的 SCJP 6 书

When to use what. I searched a lot about this.
There is no hard and fast rule.

"But As a developer, Checked exceptions must be included in a throws clause of the method. This is necessary for the compiler to know which exceptions to check.
By convention, unchecked exceptions should not be included in a throws clause.
Including them is considered to be poor programming practice. The compiler treats them as comments, and does no checking on them."

Source : SCJP 6 book by Kathy Sierra

夏の忆 2024-09-16 03:07:33

我会让你变得简单。
当您认为被调用的方法不对异常负责时(例如,调用方方法中的参数无效、要搜索的项目、在集合中获取的数据不可用或获取数据列表),请使用 throws。
当您认为被调用方法中的功能可能会导致某些异常时,请使用 try catch 块(处理被调用方法中的异常)

I ll make it simple for you.
Use throws when you think that the called method is not responsible for the exception (e.g., Invalid parameters from the caller method, item to be searched, fetched not available in the collections or fetch datalist).
Use try catch block(handle the exception in the called method) when you think that your functionality in the called method may result in some exception

向地狱狂奔 2024-09-16 03:07:33

如果使用try catch,当异常发生时,剩余的代码仍然会被执行。

如果指定抛出异常的方法,那么当异常发生时,代码将立即停止执行。

If you use a try catch, when the exception occurs, the remaining codes would be still executed.

If you indicate the method to throw the exception, then when the exception occurs, the code would stop being executed right away.

貪欢 2024-09-16 03:07:33

当您想要提供自定义行为时,请使用 try-catch 对,以防发生异常......换句话说......您可以根据程序要求解决问题(异常发生)......但是

当你对异常发生的情况没有任何具体的解决方案时,就会使用 throws...你只是不想让程序异常终止...

希望它是正确的:-)

try-catch pair is used when you want to provide customise behaviour, in case if exception occurs.....in other words...you have a solution of your problem (exception occurrence) as per your programme requirements.....

But throws is used when you don't have any specific solution regarding the exception occurrence case...you just don't want to get abnormal termination of your programme....

Hope it is correct :-)

若水微香 2024-09-16 03:07:32
  • 仅当您能够以有意义的方式处理异常时才捕获异常
  • 声明如果要由当前方法的使用者处理则向上
  • 抛出异常 如果输入参数引起则抛出异常(但这些通常是未经检查的)
  • catch an exception only if you can handle it in a meaningful way
  • declare throwing the exception upward if it is to be handled by the consumer of the current method
  • throw exceptions if they are caused by the input parameters (but these are more often unchecked)
北凤男飞 2024-09-16 03:07:32

一般来说,当一个方法无法在本地处理相关问题时,它应该向其调用者抛出异常。例如,如果该方法应该从具有给定路径的文件中读取,则无法以合理的方式在本地处理 IOExceptions。这同样适用于无效输入,并补充说我个人的选择是抛出未经检查的异常,例如在这种情况下的 IllegalArgumentException

它应该从被调用的方法中捕获异常,如果:

  • 它是可以在本地处理的东西(例如,尝试将输入字符串转换为数字,如果转换失败,则返回默认值是完全有效的) ,
  • 或者它不应该被抛出(例如,如果异常来自特定于实现的较低层,其实现细节不应该对调用者可见——例如,我不想显示我的DAO 使用 Hibernate 来持久化我的实体,因此我在本地捕获所有 HibernateExceptions 并将它们转换为我自己的异常类型)。

In general, a method should throw an exception to its caller when it can't handle the associated problem locally. E.g. if the method is supposed to read from a file with the given path, IOExceptions can't be handled locally in a sensible way. Same applies for invalid input, adding that my personal choice would be to throw an unchecked exception like IllegalArgumentException in this case.

And it should catch an exception from a called method it if:

  • it is something that can be handled locally (e.g. trying to convert an input string to a number, and if the conversion fails, it is entirely valid to return a default value instead),
  • or it should not be thrown (e.g. if the exception is coming from an implementation-specific lower layer, whose implementation details should not be visible to the caller — for example I don't want to show that my DAO uses Hibernate for persisting my entities, so I catch all HibernateExceptions locally and convert them into my own exception types).
神经暖 2024-09-16 03:07:32

这是我使用它的方式:

抛出:

  • 你只是希望代码在以下情况下停止:
    发生错误。
  • 适合容易出现问题的方法
    如果满足某些先决条件,则会出现错误
    没有遇见。

Try-Catch:

  • 当您想要该程序时
    对不同的人有不同的行为
    错误。
  • 如果您想提供,那就太好了
    对最终用户来说有意义的错误。

我知道很多人总是使用 Throws,因为它更干净,但控制权却没有那么多。

Here's the way I use it:

Throws:

  • You just want the code to stop when
    an error occurs.
  • Good with methods that are prone to
    errors if certain prerequisites are
    not met.

Try-Catch:

  • When you want to have the program
    behave differently with different
    errors.
  • Great if you want to provide
    meaningful errors to end users.

I know a lot of people who always use Throws because it's cleaner, but there's just not nearly as much control.

野の 2024-09-16 03:07:32

我个人的经验法则很简单:

  • 我可以以有意义的方式处理它(从评论中添加)吗?因此将代码放入try/catch中。通过处理它,我的意思是能够通知用户/从错误中恢复,或者从更广泛的意义上讲,能够理解此异常如何影响我的代码的执行。
  • 在其他地方,把它扔掉

注意:此回复现在是一个社区维基,请随意添加更多信息。

My personnal rule of thumb for that is simple :

  • Can I handle it in a meaningful way (added from comment)? So put code in try/catch. By handle it, I mean be able to inform the user/recover from error or, in a broader sense, be able to understand how this exception affects the execution of my code.
  • Elsewhere, throw it away

Note : this replys is now a community wiki, feel free to add more info in.

戏舞 2024-09-16 03:07:32

向方法添加 try-catch 或 throws 子句的决定取决于“您想要(或必须)如何处理异常”。

如何处理异常是一个需要回答的广泛且绝非微不足道的问题。它特别涉及决定在哪里处理异常以及在 catch 块中执行哪些操作。事实上,如何处理异常应该是全局设计决策。

所以回答你的问题,没有经验法则。

您必须决定在哪里处理异常,并且该决定通常非常具体于您的域和应用程序要求。

The decision to add a try-catch or a throws clause to your methods depends on "how you want (or have) to handle your exception".

How to handle an exception is a wide and far from trivial question to answer. It involves specially the decision of where to handle the exception and what actions to implement within the catch block. In fact, how to handle an exception should be a global design decision.

So answering your questions, there is no rule of thumb.

You have to decide where you want to handle your exception and that decision is usually very specific to your domain and application requirements.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文