简体   繁体   English

在一个catch块中使用多个异常有什么好处?

[英]What is the advantage of using multiple exceptions in one catch block?

We've all heard that in Java 7 we can write: 我们都听说过在Java 7中我们可以写:

try {
   //something with files and IO
} catch (FileNotFoundException | IOException ex) {
    ex.printStackTrace();
    System.out.println("It's can't copy file");
}

instead of 代替

try {
   //something with files and IO
} catch (FileNotFoundException wx) {
    ex.printStackTrace();
} catch (IOException ex) {
   ex.printStackTrace();
}

but, what is it really good for besides shorter code? 但是,除了更短的代码之外,它还有什么好处呢?
Even if we want the same operations done in each catch block, we can: 即使我们希望在每个catch块中完成相同的操作,我们也可以:

  1. only catch IOException because FileNotFoundException is a subtype. 只捕获IOException,因为FileNotFoundException是一个子类型。
    or 要么
  2. if one exception is not a subtype of the other one, we can write some handleException() method and call it in each catch block. 如果一个异常不是另一个异常的子类型,我们可以编写一些handleException()方法并在每个catch块中调用它。

So, is this feature only used for cleaner code or for anything else? 那么,此功能仅用于更干净的代码或其他任何内容吗?

Thanks. 谢谢。

It's not for making code look cleaner and saving key strokes. 这不是为了让代码看起来更干净并保存击键。 Those are fringe benefits. 这些都是附带福利。

Repetition leads to inconsistency and errors. 重复会导致不一致和错误。 So, by creating a syntax that makes repetition unnecessary, real errors can be avoided. 因此,通过创建不需要重复的语法,可以避免真正的错误。 That's the motivation behind DRY—not pretty code that is quicker to write. 这就是DRY背后的动机 - 不是漂亮的代码,写得更快。

是的,它主要用于更清洁的代码。

That idea is equivalent to the difference between: 这个想法相当于以下两者之间的区别:

if (myVar == true && myOtherVar == false)
    // Logic

And

if (myVar == true)
{
    if (myOtherVar == false)
        // Same logic
}

It's just shorter, cleaner code. 它只是更短,更清晰的代码。

It is for cleaner code .. but that is very valuable. 这是为了更清洁的代码...但这是非常有价值的。 In some cases you can have 4 or 5 exceptions thrown and if all you want to do is the same in all cases, which is often the case, that cuts down a lot of code. 在某些情况下,您可以抛出4或5个异常,如果您想要做的只是在所有情况下都是相同的(通常是这种情况),这会减少大量代码。

This makes it more readable and also better testable. 这使它更具可读性,也更易于测试。 That in itself is valuable enough. 这本身就足够有价值了。

The shorter code means less code for maintenance - that's not so small advantage. 较短的代码意味着更少的维护代码 - 这不是那么小的优势。 Yes, I can write exception-handling method, but now I do not do it so often, eg only when the exception is thrown in different places of code. 是的,我可以编写异常处理方法,但现在我不经常这样做,例如,只有在不同的代码位置抛出异常时。

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

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