何时在 Java 中使用异常(示例)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3213094/
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
When to use exceptions in Java (example)
提问by sixtyfootersdude
I know that this would be bad practice although I know that I would not be able to explain why.
我知道这将是不好的做法,尽管我知道我无法解释原因。
int [] intArr = ...
...
try{
int i = 0;
while(true){
System.out.println(intArr[i++]);
}
}catch(ArrayIndexOutOfBoundsException e){}
I think that you are only supposed to use exceptions for things that shouldn't happen. I am asking this question because I think that I am using exceptions wrong sometimes. If your programming is running a standard caseshould exceptions be thrown?
我认为你应该只对不应该发生的事情使用异常。我问这个问题是因为我认为我有时会错误地使用异常。如果您的程序正在运行标准情况,是否应该抛出异常?
This seems related: Preventing exceptions vs. catching exceptions in Java
这似乎相关: 在 Java 中防止异常与捕获异常
回答by Péter T?r?k
You are right: exceptions are meant for, ehm, exceptionalcases. Using them for controlling normal control flow is not only obscuring the intent of the code (which would be enough to disqualify it already), but also is much slower, since throwing and catching exceptions is costly.
你是对的:例外是为了,嗯,例外情况。使用它们来控制正常的控制流不仅模糊了代码的意图(这已经足以取消它的资格),而且速度要慢得多,因为抛出和捕获异常的成本很高。
The standard idiom (in Java5 and above) is using a foreachloop:
标准习惯用法(在 Java5 及更高版本中)使用foreach循环:
for (int i : intArr) {
System.out.println(i);
}
回答by Alberto Zaccagni
It's wrong because you knowthat eventually the loop will reach the last element of intArr, so there's nothing exceptionalin this, you're actually expectingthis behaviour.
这是错误的,因为您知道最终循环将到达 的最后一个元素intArr,因此这没有什么特别之处,您实际上期待这种行为。
回答by BalusC
Catching exceptions is only a bad practice when it concerns a RuntimeException. The ArrayIndexOutOfBoundsExceptionwhich you're trying to catch there is one.
捕获异常只是在涉及RuntimeException. 在ArrayIndexOutOfBoundsException其中你想赶上有一个。
RuntimeExceptionsidentify programmatically recoverableproblems which are caused by faults in code flow. You should not fix them by catching them, but by writing proper code and making use of flow control statements like if/else, while, for, etc.
RuntimeExceptions识别由代码流中的错误引起的可通过编程恢复的问题。你不应该通过捕获它们,而是通过写适当的代码,并利用流量控制语句喜欢的解决这些问题if/else,while,for,等。
See also:
也可以看看:
回答by Mike Q
As always "it depends" and you will find many differing opinions. Here's mine
一如既往地“视情况而定”,您会发现许多不同的意见。这是我的
- Exceptions fall into two general categories.
- Things you can reasonably anticipate and handle (FileNotFoundException)
- Things you generally don't antipicate assuming perfect code (ArrayIndexOutOfBounds)
- 例外分为两大类。
- 您可以合理预期和处理的事情 (FileNotFoundException)
- 假设完美的代码(ArrayIndexOutOfBounds),你通常不会预料到的事情
You would expect to generally handle the first category and not the latter. The latter is usually programming errors.
您通常希望处理第一个类别,而不是后者。后者通常是编程错误。
Your example falls into the latter case, a programming error. The exception is intended to give good information about the failure at runtime, not act as a control flow.
您的示例属于后一种情况,即编程错误。该异常旨在提供有关运行时故障的良好信息,而不是充当控制流。
Some people will say that the first is checked exceptions and the second is unchecked. I would disagree with that. I almost always find checked exceptions a pain in reality as you almost always end up doing catch/wrap/rethrow to another exception type. When throwing exceptions and defining my own exception classes I almost always use unchecked.
有人会说第一个是checked异常,第二个是unchecked。我不同意这一点。我几乎总是发现检查异常在现实中很痛苦,因为您几乎总是最终对另一种异常类型执行 catch/wrap/rethrow。在抛出异常和定义我自己的异常类时,我几乎总是使用 unchecked。
回答by Dean J
Exceptions should catch something exceptional, log it, and recover if possible.
异常应该捕获一些异常的东西,记录它,并在可能的情况下恢复。
If it's part of normal program flow, you should handle it normally.
如果它是正常程序流程的一部分,您应该正常处理它。
回答by UnixShadow
Exceptions are for exceptionsin the code. Not for standard cases.
异常是针对代码中的异常。不适用于标准情况。
however, there are one more serious issue with your code, it is slower the it would be without the use of exception. Creating the exception, throwing the exception and catching the exception takes additional CPU and MEMORY.
但是,您的代码有一个更严重的问题,它比不使用异常时要慢。创建异常、抛出异常和捕获异常需要额外的 CPU 和内存。
Also the code gets harder to read for other programmers that only expect Exceptions to be thrown on error cases.
此外,对于只希望在错误情况下抛出异常的其他程序员来说,代码变得更难阅读。
回答by Bill the Lizard
Reaching the end of an array is not an exceptional case. You know the length before you start looping, so just use a standard idiom.
到达数组的末尾并不是特例。您在开始循环之前就知道长度,因此只需使用标准习语即可。
for(int i = 0; i < intArr.length; ++i) {
System.out.println(intArr[i]);
}
回答by Jean-Philippe Caruana
Eating exceptions the way you do is usually considered a bad practice : if you don't have to do any further treatment, you can log it.
以您的方式吃异常通常被认为是一种不好的做法:如果您不必做任何进一步的治疗,则可以记录下来。
回答by this. __curious_geek
Only in exceptional situations like,
只有在特殊情况下,例如,
- when a method cannot do what it is supposed to do
- not to control the execution flow
- 当一个方法不能做它应该做的事情时
- 不控制执行流程
回答by akf
You are correct. Exceptions should not be used to handle process flow.
你是对的。不应使用异常来处理流程。

