抛出或尝试捕获
在决定是否向方法添加 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(11)
如果引发异常的方法有足够的信息来处理它,那么它应该捕获并生成有关发生了什么以及正在处理哪些数据的有用信息。
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.
如果方法可以对对象的状态、传递给该方法的任何参数以及该方法所作用的任何其他对象做出合理的保证,则该方法应该仅
抛出
异常。例如,如果预期存在于集合中的项目不存在,则应该从集合中检索调用者期望包含在其中的项目的方法可能会抛出
检查异常。 。捕获该异常的调用者应该期望该集合不包含有问题的项目。请注意,虽然 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 mightthrows
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 callingFullMoonException
, and is expected to throw it when the Moon is full; imagine further, thatLookAtSky()
callsExamineJupiter()
, which is also declared asthrows FullMoonException
. If aFullMoonException
were thrown byExamineJupiter()
, and ifLookAtSky()
didn't catch it and either handle it or wrap it in some other exception type, the code which calledLookAtSky
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.
什么时候用什么。我对此进行了很多搜索。
没有硬性规定。
“但是作为开发人员,受检查的异常必须包含在方法的 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
我会让你变得简单。
当您认为被调用的方法不对异常负责时(例如,调用方方法中的参数无效、要搜索的项目、在集合中获取的数据不可用或获取数据列表),请使用 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
如果使用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.
当您想要提供自定义行为时,请使用 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 :-)
一般来说,当一个方法无法在本地处理相关问题时,它应该向其调用者抛出异常。例如,如果该方法应该从具有给定路径的文件中读取,则无法以合理的方式在本地处理 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 likeIllegalArgumentException
in this case.And it should catch an exception from a called method it if:
DAO
usesHibernate
for persisting my entities, so I catch allHibernateExceptions
locally and convert them into my own exception types).这是我使用它的方式:
抛出:
发生错误。
如果满足某些先决条件,则会出现错误
没有遇见。
Try-Catch:
对不同的人有不同的行为
错误。
对最终用户来说有意义的错误。
我知道很多人总是使用 Throws,因为它更干净,但控制权却没有那么多。
Here's the way I use it:
Throws:
an error occurs.
errors if certain prerequisites are
not met.
Try-Catch:
behave differently with different
errors.
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.
我个人的经验法则很简单:
try/catch
中。通过处理它,我的意思是能够通知用户/从错误中恢复,或者从更广泛的意义上讲,能够理解此异常如何影响我的代码的执行。注意:此回复现在是一个社区维基,请随意添加更多信息。
My personnal rule of thumb for that is simple :
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.Note : this replys is now a community wiki, feel free to add more info in.
向方法添加 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.