Java:捕获特定的异常 [英] Java: catching specific Exceptions

查看:104
本文介绍了Java:捕获特定的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有以下

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆