Java中如何检查抛出的异常类型?

2024-04-23

如果一个操作捕获了多个异常,如何确定捕获了哪种类型的异常?

这个例子应该更有意义:

try {
  int x = doSomething();
} catch (NotAnInt | ParseError e) {
  if (/* thrown error is NotAnInt */) {    // line 5
    // printSomething
  } else {
    // print something else
  }
}

在第 5 行,如何检查捕获了哪个异常?

I tried if (e.equals(NotAnInt.class)) {..}但没有运气。

NOTE: NotAnInt and ParseError我的项目中的类是扩展的Exception.


如果可以的话,always使用单独的catch阻止个别异常类型,没有理由这样做:

} catch (NotAnInt e) {
    // handling for NotAnInt
} catch (ParseError e) {
    // handling for ParseError
}

...除非您需要共享一些共同的步骤,并且出于简洁的原因想要避免使用其他方法:

} catch (NotAnInt | ParseError e) {
    // a step or two in common to both cases
    if (e instanceof NotAnInt) {
        // handling for NotAnInt
    } else  {
        // handling for ParseError
    }
    // potentially another step or two in common to both cases
}

然而,共同的步骤也可以提取为方法来避免这种情况if-else block:

} catch (NotAnInt e) {
    inCommon1(e);
    // handling for NotAnInt
    inCommon2(e);
} catch (ParseError e) {
    inCommon1(e);
    // handling for ParseError
    inCommon2(e);
}

private void inCommon1(e) {
    // several steps
    // common to
    // both cases
}
private void inCommon2(e) {
    // several steps
    // common to
    // both cases
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Java中如何检查抛出的异常类型? 的相关文章