ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
### [多重捕获](https://lingcoder.gitee.io/onjava8/#/book/15-Exceptions?id=%e5%a4%9a%e9%87%8d%e6%8d%95%e8%8e%b7) 如果有一组具有相同基类的异常,你想使用同一方式进行捕获,那你直接 catch 它们的基类型。但是,如果这些异常没有共同的基类型,在 Java 7 之前,你必须为每一个类型编写一个 catch: ~~~ // exceptions/SameHandler.java class EBase1 extends Exception {} class Except1 extends EBase1 {} class EBase2 extends Exception {} class Except2 extends EBase2 {} class EBase3 extends Exception {} class Except3 extends EBase3 {} class EBase4 extends Exception {} class Except4 extends EBase4 {} public class SameHandler { void x() throws Except1, Except2, Except3, Except4 {} void process() {} void f() { try { x(); } catch(Except1 e) { process(); } catch(Except2 e) { process(); } catch(Except3 e) { process(); } catch(Except4 e) { process(); } } } ~~~ 通过 Java 7 的多重捕获机制,你可以使用“或”将不同类型的异常组合起来,只需要一行 catch 语句: ~~~ // exceptions/MultiCatch.java public class MultiCatch { void x() throws Except1, Except2, Except3, Except4 {} void process() {} void f() { try { x(); } catch(Except1 | Except2 | Except3 | Except4 e) { process(); } } } ~~~ 或者以其他的组合方式: ~~~ // exceptions/MultiCatch2.java public class MultiCatch2 { void x() throws Except1, Except2, Except3, Except4 {} void process1() {} void process2() {} void f() { try { x(); } catch(Except1 | Except2 e) { process1(); } catch(Except3 | Except4 e) { process2(); } } } ~~~ 这对书写更整洁的代码很有帮助。