Java:捕获特定的异常 [英] Java: catching specific Exceptions
问题描述
说我有以下
try{
//something
}catch(Exception generic){
//catch all
}catch(SpecificException se){
//catch specific exception only
}
遇到SpecificException会发生什么?它首先将它作为通用异常捕获,然后捕获特定的异常吗?
What would happen when it comes across SpecificException ? Does it catch it as a generic exception first, and then catch the specificexception ?
或者它只捕获SpecificException而忽略一般异常。
Or does it only catch SpecificException while ignoring generic exceptions.
我不希望被捕获泛型和特殊化。
I don't want both generic and specificexception being caught.
推荐答案
不。所有异常都将被第一个块捕获。永远不会达到第二个(编译器识别,导致由于无法访问的代码而导致错误)。如果你想特别对待 SpecificException
,你必须反过来这样做:
No. All exceptions would be caught by the first block. The second will never be reached (which the compiler recognizes, leading to an error due to unreachable code). If you want to treat SpecificException
specifically, you have to do it the other way round:
}catch(SpecificException se){
//catch specific exception only
}catch(Exception generic){
//catch all
}
然后 SpecificException
将被第一个块捕获,并且所有第二个人。
Then SpecificException
will be caught by the first block, and all others by the second.
这篇关于Java:捕获特定的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!