java Try/Multi-Catch vs Single Catch
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17635545/
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
Try/Multi-Catch vs Single Catch
提问by Aaron
While adding a try/catch block in Eclipse, it gave me the option of "Surround with try/multi-catch" or "Surround with try/catch."
在 Eclipse 中添加 try/catch 块时,它为我提供了“环绕与 try/multi-catch”或“环绕与 try/catch”的选项。
This is the try/multi-catch:
这是 try/multi-catch:
try {
save.load(new FileInputStream(file.getAbsolutePath()));
}
catch (FileNotFoundException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This is the single try/catch:
这是单个尝试/捕获:
try {
save.load(new FileInputStream(file.getAbsolutePath()));
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
What are the benefits/repercussions of using one or the other? If I'm correct, the first example will execute the catch block when EITHER of the exceptions are thrown and produce the SAME CATCH, while the second example will throw a catch based on the exception while enabling separate catch blocks.
使用一种或另一种的好处/影响是什么?如果我是对的,第一个示例将在抛出任何一个异常并产生 SAME CATCH 时执行 catch 块,而第二个示例将在启用单独的 catch 块的同时根据异常抛出一个 catch 块。
Is there anything else I should know about this? I've never used them before and don't know if they are worth using.
还有什么我应该知道的吗?我以前从未使用过它们,不知道它们是否值得使用。
采纳答案by nanofarad
tl;drMutlicatch handles things singlehandedly, multiple catch blocks are more flexible and nicer to operations. The two techniques can be combined.
tl;drMutlicatch 单独处理事情,多个 catch 块更灵活,更适合操作。这两种技术可以结合使用。
If you have a try statement that can throw many different exception types, you'll want the multiple catch blocks. It's a bit more code but offers far greater flexibility.
如果您有一个可以抛出许多不同异常类型的 try 语句,您将需要多个 catch 块。这是更多的代码,但提供了更大的灵活性。
For instance, if working with sockets, a SocketException may be caught with nothing more than a reconnect and/or an error message (as something as simple as an inadvertently disconnected cable may cause this)
例如,如果使用套接字,则可能会捕获 SocketException,而不会超过重新连接和/或错误消息(就像无意中断开的电缆可能导致这种情况一样简单)
If a null pointer exception(although it's unchecked) is caught, you're going to want to write to a log and make an emergency landing here, cleaning up what you can, and backtracking quite a bit codewise, possibly.
如果捕获到空指针异常(尽管它未经检查),您将想要写入日志并紧急登陆这里,清理您所能做的事情,并可能在代码上进行相当多的回溯。
In addition, this can be subdivided even further, where different types of "common" exceptions may cause different actions to be taken(such as a connection lost vs name not resolved having different implications for the end-user on the first connection attempt) and different "heavy" exceptions being handled in different ways as well.
此外,这可以进一步细分,其中不同类型的“常见”异常可能导致采取不同的操作(例如连接丢失与名称未解析对第一次连接尝试对最终用户产生不同影响)和不同的“重”异常也以不同的方式处理。
While you could have one (multiple exception type) catch block, it would either singlehandedly take similar action for all exceptions (presenting a null pointer exception to a user in the same way as a condition based on a cable being unplugged) or require if e instanceof FooException
blocks that can decrease readability.
虽然您可以拥有一个(多个异常类型)catch 块,但它会单独对所有异常采取类似的操作(向用户呈现空指针异常与基于电缆被拔出的情况相同的方式)或需要if e instanceof FooException
块会降低可读性。
You can also combine the two, multicatching all "common" exceptions into a retry and nice message and all severe exceptions into a forced cleanup and shutdown
您还可以将两者结合起来,将所有“常见”异常多重捕获为重试和好的消息,将所有严重异常捕获为强制清理和关闭
You don't want stacktraces for tripped cables, and you don't want to brush off missing objects.
您不希望绊倒电缆的堆栈跟踪,也不想刷掉丢失的对象。
回答by Ahmed Masud
This a choice thing. You want to balance readability, portability, maintainability and also handling different exceptions differently.
这是一个选择的事情。您想要平衡可读性、可移植性、可维护性以及以不同方式处理不同的异常。
So balance the use ... If all your catches use the same block of handling then use the first form, because that's just one code block and you aren't repeating yourself over and over again. The compiler can optimize things out a bit for you.
所以平衡使用......如果你所有的捕获使用相同的处理块,那么使用第一种形式,因为那只是一个代码块,你不会一遍又一遍地重复自己。编译器可以为您优化一些东西。
On the other hand use the second form if you are handling each exception differently.
另一方面,如果您以不同方式处理每个异常,请使用第二种形式。
This is somewhat of a broad question and the answer is dependant on your goals.
这是一个比较宽泛的问题,答案取决于您的目标。
回答by KyelJmD
I believe that your first code snippet will only be applicable if your JDK is Java JDK 7. while the second snippet will still run in JDK 7 and below.
我相信您的第一个代码片段仅在您的 JDK 是 Java JDK 7 时才适用。而第二个代码片段仍将在 JDK 7 及以下版本中运行。
If you have a line of code that is possible to throw different types of exception and you want to handle them all in a similar way, Multicatch will fit you since it saves several lines of code.
如果您有一行代码可以抛出不同类型的异常,并且您想以类似的方式处理它们,Multicatch 将适合您,因为它节省了几行代码。
however, if you have a line of code that will throw several exceptions, and you want to handle those exceptions individually, a single catch exception will fit you more.
但是,如果您有一行代码会抛出多个异常,并且您想单独处理这些异常,那么单个 catch 异常将更适合您。
回答by johnchen902
If you want to do the same thing for all exceptions, try-multi catch and try-catch are the same, except the former is shorter. All programmers are lazy.
如果你想对所有异常都做同样的事情,try-multi catch 和 try-catch 是一样的,只是前者较短。所有的程序员都是懒惰的。
When you want to do different thing for different exceptions:
当你想为不同的异常做不同的事情时:
} catch(AException e) {
System.err.println("AException occured");
} catch(BException e) {
System.err.println("BException occured");
}
Try-multi catch is not the right choice.
Try-multi catch 不是正确的选择。
} catch(AException | BException e) {
System.err.println("A or B Exception occured");
}
Note that the type of e
is the nearest common supertype of AException
and BException
.
请注意, 的类型e
是AException
and的最接近的公共超类型BException
。
回答by Joe Babcock
Look, the actualutility of try-catch structures is that you can apply a specific error-handling function to a specific exception. In your case, it doesn't appear that you want anything to happen other than a stack trace to be printed. If I, for instance, wanted the window to close if a FileIOException was thrown, and I wanted simply an error message to appear if any other exception occurs, then it would be useful to have multiple try-catch blocks as you wrote in the second code block. In this application, though, you may just want to have a catch like this:
看,try-catch 结构的实际用途是您可以将特定的错误处理函数应用于特定的异常。在您的情况下,除了要打印堆栈跟踪之外,您似乎不希望发生任何事情。例如,如果我希望在抛出 FileIOException 时关闭窗口,并且我只想在发生任何其他异常时显示一条错误消息,那么拥有多个 try-catch 块会很有用,如您在第二个中所写代码块。但是,在此应用程序中,您可能只想捕获如下内容:
try {
save.load(new FileInputStream(file.getAbsolutePath()));
} catch (Exception e) {
e.printStackTrace();
}
And that will print a strack trace for ALL exceptions. :)
这将打印所有异常的跟踪跟踪。:)