Managing multiple exceptions Java7

I have been trying to find out answer to this question but did not get any satisfactory explanation. Here is some background:

Java 7 allows us to catch multiple exceptions in a single catch block provided those exceptions are from diffrent hierarchy. Eg:

try {
    // some code

} catch(SQLException | FileNotFoundException e) {
    e.printStackTrace();
} catch(Exception e) {
    e.printStackTrace();
}

But if exceptions are from the same hierarchy we must use multiple catch blocks like:

try {
    // some code
} catch(FileNotFoundException  e) {
    e.printStackTrace();
} catch(IOException e) {
    e.printStackTrace();
}

But if I try to write code like below compiler complains that “The exception FileNotFoundException
is already caught by the alternative IOException

try {
    // some code
} catch(FileNotFoundException | IOException  e) { // compiler error
    e.printStackTrace();
}

Now my question is: Why compiler reports an error in last case, can’t it figure out that FileNotFoundException
is special case of IOException
? This would save code duplication when my exception handling logic is same.

Why compiler reports an error in last case, can’t it figure out that FileNotFoundException
is special case of IOException
?

Because FileNotFoundException
is a subclass of IOException
. In other words, the ” FileNotFoundException |
” part is redundant.

The reason why the code below is ok…

} catch(FileNotFoundException  e) {
    ...
} catch(IOException e) {
    ...
}

…is because here the IOException
clause matters: If a SocketException
is thrown for instance, it will pass the by the FileNotFoundException
part, and get caught in the IOException
clause.

Hello, buddy!稿源:Hello, buddy! (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 综合编程 » Managing multiple exceptions Java7

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录