在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 (IllegalArgumentException | SecurityException | IllegalAccessException | NoSuchFieldException e) { someCode(); }
但请记住,如果所有异常都属于同一个类层次结构,您可以简单地捕获该基本异常类型。
另请注意,如果直接或间接地ExceptionA从. 编译器会抱怨:ExceptionB``ExceptionB``ExceptionA
ExceptionA
ExceptionB``ExceptionB``ExceptionA
Alternatives in a multi-catch statement cannot be related by subclassing Alternative ExceptionB is a subclass of alternative ExceptionA
对此的修复是只在异常列表中包含祖先异常,因为它也会捕获后代类型的异常。