在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(); }
有什么办法吗?
从Java 7开始,这已经成为可能。多捕获块的语法为:
try { ... } catch (IOException | SQLException ex) { ... }
但是请记住,如果所有异常都属于同一类层次结构,则可以简单地捕获该基本异常类型。
还要注意,如果从ExceptionA直接或间接继承了ExceptionB,则不能在同一块中同时捕获ExceptionA和ExceptionB。编译器会抱怨:
Alternatives in a multi-catch statement cannot be related by subclassing Alternative ExceptionB is a subclass of alternative ExceptionA