简体   繁体   English

投掷或尝试捕捉

[英]Throws or try-catch

What is the general rule of thumb when deciding whether to add a throws clause to a method or using a try-catch ?在决定是向方法添加throws子句还是使用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.根据我自己的阅读,当调用者破坏了他们的合同(传递的对象)结束时应该使用throws ,并且当在内部执行的操作期间发生异常时应该使用try-catch方法。 Is this correct?这样对吗? If so, what should be done on the callers side?如果是这样,调用方应该怎么做?

PS: Searched through Google and SO but would like a clear answer on this one. PS:通过 Google 和 SO 进行搜索,但想要一个明确的答案。

  • 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)如果它们是由输入参数引起的,则抛出异常(但这些通常是未经检查的)

In general, a method should throw an exception to its caller when it can't handle the associated problem locally.一般来说,当一个方法不能在本地处理相关问题时,它应该向它的调用者抛出一个异常。 Eg if the method is supposed to read from a file with the given path, IOExceptions can't be handled locally in a sensible way.例如,如果该方法应该从具有给定路径的文件中读取,则无法以合理的方式在本地处理IOExceptions Same applies for invalid input, adding that my personal choice would be to throw an unchecked exception like IllegalArgumentException in this case.同样适用于无效输入,并补充说我个人的选择是在这种情况下抛出一个未经检查的异常,如IllegalArgumentException

And it should catch an exception from a called method it if:如果出现以下情况,它应该从被调用的方法中捕获异常:

  • it is something that can be handled locally (eg 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 (eg 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).或者它不应该被抛出(例如,如果异常来自特定于实现的较低层,其实现细节不应该对调用者可见——例如,我不想表明我的DAO使用Hibernate来持久化我的实体,所以我在本地捕获所有HibernateExceptions并将它们转换为我自己的异常类型)。

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.我知道很多人总是使用 Throws,因为它更干净,但几乎没有那么多控制。

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 .所以把代码放在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.注意:此回复现在是社区维基,请随时添加更多信息。

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".向您的方法添加 try-catch 或 throws 子句的决定取决于“您希望(或必须)如何处理您的异常”。

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.它特别涉及在何处处理异常以及在 catch 块中实现哪些操作的决定。 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.您必须决定在何处处理异常,并且该决定通常非常特定于您的域和应用程序要求。

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

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.如果一个方法可以对对象的状态、传递给该方法的任何参数以及该方法作用于的任何其他对象做出合理的保证,该方法应该只throws异常。 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.例如,如果预期存在于集合中的项目不存在,则应该从集合中检索调用者期望包含在其中的项目的方法可能会throws已检查的异常。 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.请注意,虽然 Java 允许检查异常通过声明为抛出适当类型的异常的方法冒泡,但这种用法通常应被视为反模式。 Imagine, for example, that some method LookAtSky() is declared as calling FullMoonException , and is expected to throw it when the Moon is full;想象一下,例如,某个方法LookAtSky()被声明为调用FullMoonException ,并且预计在满月时抛出它; imagine further, that LookAtSky() calls ExamineJupiter() , which is also declared as throws FullMoonException .进一步想象一下, LookAtSky()调用了ExamineJupiter() ,它也被声明为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;如果FullMoonException被抛出ExamineJupiter()如果LookAtSky()没抓住,要么办理或者在其他一些异常类型包装它,它调用的代码LookAtSky将承担例外是地球的卫星已满结果; 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 (eg 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.如果调用者不期望抛出异常,则调用者不能期望它具有任何特定含义。

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. “但作为开发人员,Checked 异常必须包含在方法的 throws 子句中。这是编译器知道要检查哪些异常所必需的。按照惯例,未检查异常不应包含在 throws 子句中。
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资料来源:Kathy Sierra 的 SCJP 6 书

I ll make it simple for you.我会为你简单化。 Use throws when you think that the called method is not responsible for the exception (eg, Invalid parameters from the caller method, item to be searched, fetched not available in the collections or fetch datalist).当您认为被调用的方法不应对异常负责时使用 throws(例如,来自调用者方法的无效参数、要搜索的项目、集合中不可用的获取或获取数据列表)。 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当您认为被调用方法中的功能可能会导致某些异常时,请使用 try catch 块(处理被调用方法中的异常)

If you use a try catch, when the exception occurs, the remaining codes would be still executed.如果使用try catch,当异常发生时,剩余的代码仍会被执行。

If you indicate the method to throw the exception, then when the exception occurs, the code would stop being executed right away.如果指定了抛出异常的方法,那么当异常发生时,代码会立即停止执行。

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

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....但是,当您对异常发生的情况没有任何具体解决方案时使用 throws ......你只是不想让你的程序异常终止......

Hope it is correct :-)希望它是正确的:-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM