繁体   English   中英

捕获未引发的检查异常

[英]Catching non thrown checked exception

我有一个通过EJB调用外部API的代码,并且该API偶尔会泄漏不属于客户端工具包的异常,因此导致ClassNotFoundException

我在电话周围有一个try-catch块:

    try {
      thirdPartyLibrary.finalInvokeMethod();
    } catch (SomeException exception) {
      //Do something
    } catch(
    ..
    } catch (Exception exception) {
      if (exception instanceof ClassNotFoundException) {
         log.error("....");
      }
    }

我想避免在catch中使用instanceof,但是如果我为ClassNotFoundException添加单独的catch子句,则由于thirdPartyLibrary.finalInvokeMethod();编译器会产生错误“ Unreachable catch block” thirdPartyLibrary.finalInvokeMethod(); 不会抛出ClassNotFoundException

有没有更好的方法来解决这个问题?

我找到了一种解决方法。 我已经包装了thirdPartyLibrary.finalInvokeMethod(); 在另一种引发检查异常的方法中。 因此,我得到了一个专用的catch子句,没有编译器错误。

private someMethod() {
  try {
    callExternalAPI();
  } catch (SomeException exception) {
    //Do something
  } catch(
  ..
  } catch (ClassNotFoundException exception) {
    log.error("....");
    //Do something
  } catch (Exception exception) {
    //Do something
  }
}

private void callExternalAPI() throws ClassNotFoundException {
  thirdPartyLibrary.finalInvokeMethod();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM