簡體   English   中英

Java:如何在try catch體內向方法調用者拋出異常?

[英]Java: How to throw an Exception to the method caller inside a try catch body?

當我有這樣的方法:

public static void foo(String param) throws IOException
{
    try
    {
         // some IOoperations
         if (param.isEmpty())
         {
              throw new IOException("param is empty");
         }
         // some other IOoperations

    } catch (Exception e) {
        /* handle some possible errors of of the IOoperations */
    }
}

當拋出IOException(“param為空”)時,它會被該體中的try-catch 但是此異常適用於此方法的調用者。 我該怎么做呢? 是否有“pure-Java”這樣做或者我是否必須創建另一種類型的Exception,它不是IOException的實例以避免try-catch體將處理它?

我知道你會建議在這種情況下使用IllegalArgumentException 但這是我情況的簡化示例。 事實上, 拋出的異常是一個IOException。

謝謝

制作自己的IOException自定義子類可能是個好主意。 不僅要解決這個問題,而且有時候對於API用戶來說,它有點'用戶友好'。

然后你可以在catch塊中忽略它(立即重新拋出它)

} catch (FooIOException e) {
    throw e;
} catch (Exception e) {
    /* handle some possible errors of of the IOoperations */
}

我覺得我對你的例子的具體細節感到困惑 - 你為什么要做廣泛的

} catch (Exception e) {

如果沒有那個過於通用的catch子句,你的問題就會消失。

我誤會了嗎?

您可以檢查您的異常是否是IOException的實例,如果是,請重新拋出它。

catch( Exception e ) {
  if( e instanceof IOException ) {
    throw (IOException)e;
  }
}

你可以捕獲它並重新拋出它,但正確的解決方案應該是更有選擇性地捕獲你在catch語句中捕獲的內容....

例如。 在下面的代碼中,我捕獲了一個FileNotFoundException,因此IOException被拋回到調用方法。

public static void foo(String param) throws IOException {
        try {
         // some IOoperations
         if (param.isEmpty())
         {
              throw new IOException("param is empty");
         }
         // some other IOoperations

        } catch (FileNotFoundException e) {
            /* handle some possible errors of of the IOoperations */
        }
    }

我會創建一個IOException的子類。 這將允許您使用instanceof檢查和重新拋出。

我使用catch (Exception)情況非常少。 捕獲特定異常幾乎總是更好。 唯一的原因是你想要聚合異常和重新拋出(反射操作是一個常見的地方)。

如果IOExceptions適用於foo()調用者,則可以執行以下操作:

public static void foo(String param) throws IOException
{
    try
    {
         // some IOoperations
         if (param.isEmpty())
         {
              throw new IOException("param is empty");
         }
         // some other IOoperations

    } catch (IOException e) {
        throw e;
    } catch (Exception e) {
        /* handle some possible errors of of the IOoperations */
    }

}

如果您的異常是唯一真正需要重新拋出的異常,那么創建一個新的IOException子類型名稱MyException嘗試捕獲MyException以重新拋出它。

任何寵物小精靈異常處理都非常難看!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM