简体   繁体   English

捕获未引发的检查异常

[英]Catching non thrown checked exception

I have a code that invokes an external API via EJB and that API occasionally leaks an exception that is not part of the client kit, therefore resulting in ClassNotFoundException . 我有一个通过EJB调用外部API的代码,并且该API偶尔会泄漏不属于客户端工具包的异常,因此导致ClassNotFoundException

I have a try-catch block surrounding the call: 我在电话周围有一个try-catch块:

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

I want to avoid using instanceof in catch, but if I add a separate catch clause for ClassNotFoundException , the compiler produces an error "Unreachable catch block", since thirdPartyLibrary.finalInvokeMethod(); 我想避免在catch中使用instanceof,但是如果我为ClassNotFoundException添加单独的catch子句,则由于thirdPartyLibrary.finalInvokeMethod();编译器会产生错误“ Unreachable catch block” thirdPartyLibrary.finalInvokeMethod(); doesn't throw ClassNotFoundException . 不会抛出ClassNotFoundException

Is there a better way to address the issue? 有没有更好的方法来解决这个问题?

I've found a workaround. 我找到了一种解决方法。 I've wrapped the thirdPartyLibrary.finalInvokeMethod(); 我已经包装了thirdPartyLibrary.finalInvokeMethod(); in another method that throws the checked exception. 在另一种引发检查异常的方法中。 So I got a dedicated catch clause without a compiler error. 因此,我得到了一个专用的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