2015-10-21 42 views
1

我有一個通過EJB調用外部API的代碼,該API偶爾會泄漏不屬於客戶端工具包的異常,因此導致ClassNotFoundException捕獲未拋出的已檢查異常

我周圍的調用try-catch塊:

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

我想避免在抓使用的instanceof,但如果我添加一個單獨的catch子句爲ClassNotFoundException,編譯器產生一個錯誤「無法到達抓塊「,因爲thirdPartyLibrary.finalInvokeMethod();不會丟ClassNotFoundException

有沒有更好的方法來解決這個問題?

+1

如果方法thirdPartyLibrary.finalInvokeMethod();沒有給出一個ClassNotFoundException,它怎麼能捕獲一個ClassNotFoundException?問題可能在不同的地方。 – Cyrex

+0

我覺得你很困惑'ClassNotFoundException'和'NoClassDefFoundError'。如果你想捕捉後者,你可以有一個catch塊,沒有任何編譯錯誤。 –

+0

RMI機制通過反射和反序列化來重構來自外部API的回覆,因此如果它在類路徑中沒有泄漏異常,則拋出'ClassNotFoundException'。 (因此我不會混淆'ClassNotFoundException'和'NoClassDefFoundError') – Boris

回答

1

我找到了解決方法。我將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(); 
} 
相關問題