Java 投掷或尝试捕捉
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3203297/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Throws or try-catch
提问by James P.
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. Is this correct? If so, what should be done on the callers side?
从我自己读过的内容来看,throws
应该在调用者违反合同(传递的对象)结束try-catch
时使用,并且应该在方法内部执行的操作期间发生异常时使用。这样对吗?如果是这样,调用方应该怎么做?
P.S: Searched through Google and SO but would like a clear answer on this one.
PS:通过 Google 和 SO 进行搜索,但想要一个明确的答案。
采纳答案by Bozho
- 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)
- 仅当您可以以有意义的方式处理异常时才捕获异常
- 如果要由当前方法的使用者处理,则声明向上抛出异常
- 如果它们是由输入参数引起的,则抛出异常(但这些通常是未经检查的)
回答by Péter T?r?k
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.
一般来说,当一个方法不能在本地处理相关问题时,它应该向它的调用者抛出一个异常。例如,如果该方法应该从具有给定路径的文件中读取,IOExceptions
则无法以合理的方式在本地进行处理。同样适用于无效输入,并补充说我个人的选择是IllegalArgumentException
在这种情况下抛出未经检查的异常。
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
usesHibernate
for persisting my entities, so I catch allHibernateExceptions
locally and convert them into my own exception types).
- 它是可以在本地处理的东西(例如,尝试将输入字符串转换为数字,如果转换失败,则返回默认值是完全有效的),
- 或者它不应该被抛出(例如,如果异常来自特定于实现的较低层,其实现细节对调用者不应该是可见的——例如,我不想展示我用于持久化实体的
DAO
用途Hibernate
,所以我HibernateExceptions
在本地捕获所有并将它们转换为我自己的异常类型)。
回答by Riduidel
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
- 我能以有意义的方式处理它吗(从评论中添加)?所以把代码放在
try/catch
. 通过处理它,我的意思是能够通知用户/从错误中恢复,或者从更广泛的意义上讲,能够理解此异常如何影响我的代码的执行。 - 在别处扔掉
Note : this replys is now a community wiki, feel free to add more info in.
注意:此回复现在是社区维基,请随时添加更多信息。
回答by Alberto Zaccagni
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.
如果引发异常的方法有足够的信息来处理它,那么它应该捕获,生成关于发生了什么以及正在处理什么数据的有用信息。
回答by Justian Meyer
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 meaningfulerrors 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,因为它更干净,但几乎没有那么多控制。
回答by EijiAdachi
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. In fact, how to handle an exception should be a global design decision.
如何处理异常是一个需要回答的广泛而远非微不足道的问题。它特别涉及在何处处理异常以及在 catch 块中实现哪些操作的决定。事实上,如何处理异常应该是一个全局的设计决定。
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.
您必须决定在何处处理异常,并且该决定通常非常特定于您的域和应用程序要求。
回答by supercat
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.
如果一个方法throws
可以对对象的状态、传递给该方法的任何参数以及该方法作用于的任何其他对象做出合理的保证,它就应该是一个例外。例如,throws
如果预期存在于集合中的项目不存在,则应该从集合中检索调用者期望包含在其中的项目的方法可能会出现检查异常。捕获该异常的调用者应该期望集合不包含相关项目。
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.
请注意,虽然 Java 允许检查异常通过声明为抛出适当类型的异常的方法冒泡,但这种用法通常应被视为反模式。想象一下,例如,某个方法LookAtSky()
被声明为调用FullMoonException
,并期望在满月时抛出它;进一步想象一下,那个LookAtSky()
调用ExamineJupiter()
,它也被声明为throws FullMoonException
。如果 aFullMoonException
由 抛出ExamineJupiter()
,并且LookAtSky()
没有捕获它并处理它或将其包装在其他一些异常类型中,则调用的代码LookAtSky
将假定异常是地球满月的结果;它不知道木星的一颗卫星可能是罪魁祸首。
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.
调用者可能期望处理的异常(包括基本上所有已检查的异常)应该只允许通过一个方法向上渗透,前提是该异常对方法的调用者意味着与对被调用方法的意义相同的事情。如果代码调用了一个声明为抛出一些受检异常的方法,但调用者并不期望它在实践中抛出该异常(例如,因为它认为它预先验证了方法参数),则应捕获并包装受检异常在一些未经检查的异常类型中。如果调用者不期望抛出异常,则调用者不能期望它具有任何特定含义。
回答by Jarkid
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.
如果指定了抛出异常的方法,那么当异常发生时,代码会立即停止执行。
回答by user8148636
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 :-)
希望它是正确的:-)
回答by sofs1
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."
“但作为开发人员,Checked 异常必须包含在方法的 throws 子句中。这对于编译器知道要检查哪些异常是必要的。按照惯例,未检查异常不应包含在 throws 子句中。
包括它们是被考虑的是糟糕的编程实践。编译器将它们视为注释,并且不检查它们。”
Source : SCJP 6 book by Kathy Sierra
资料来源:Kathy Sierra 的 SCJP 6 书