我可以在同一个catch子句中捕获多个Java异常吗?在Java中,我想做这样的事情:try {
... } catch (/* code to catch IllegalArgumentException, SecurityException,
IllegalAccessException, and NoSuchFieldException at the same time */) {
someCode();}...代替:try {
... } catch (IllegalArgumentException e) {
someCode();} catch (SecurityException e) {
someCode();} catch (IllegalAccessException e) {
someCode();} catch (NoSuchFieldException e) {
someCode();}有没有办法做到这一点?
3 回答
千万里不及你
TA贡献1784条经验 获得超9个赞
自Java 7以来,这是可能的。多捕获块的语法是:
try { ...} catch (IOException | SQLException ex) { ...}
但请记住,如果所有异常都属于同一个类层次结构,则可以简单地捕获该基本异常类型。
另请注意,如果ExceptionB直接或间接地从ExceptionA继承,则无法在同一块中捕获ExceptionA和ExceptionB。编译器会抱怨:
Alternatives in a multi-catch statement cannot be related by subclassing Alternative ExceptionB is a subclass of alternative ExceptionA
繁华开满天机
TA贡献1816条经验 获得超4个赞
不完全是在Java 7之前,但我会做这样的事情:
Java 6和之前的版本
try { //.....} catch (Exception exc) { if (exc instanceof IllegalArgumentException || exc instanceof SecurityException || exc instanceof IllegalAccessException || exc instanceof NoSuchFieldException ) { someCode(); } else if (exc instanceof RuntimeException) { throw (RuntimeException) exc; } else { throw new RuntimeException(exc); }}
Java 7
try { //.....} catch ( IllegalArgumentException | SecurityException | IllegalAccessException |NoSuchFieldException exc) { someCode();}
斯蒂芬大帝
TA贡献1827条经验 获得超8个赞
在Java 7中,您可以定义多个catch子句,如:
catch (IllegalArgumentException | SecurityException e){ ...}
添加回答
举报
0/150
提交
取消