2017-01-03 41 views
0

即使methodA1()存在異常,我也需要methodA2執行。在這裏,我只添加了兩個方法methodA1()和methodA2()。假設有很多方法。在這種情況下,解決方案應該能夠適用。在所有行完成執行而沒有最終執行後處理異常

 class A { 
      String methodA1() throws ExceptionE { 
       // do something 
      } 

      String methodA2() throws ExceptionE { 
       // do something 
      } 
     } 

     class C extends A { 
       String methodC() throws ExceptionE2 { 
       try { 
        methodA1(); 
        methodA2(); 
       } catch (ExceptionE e) { 
        throw new ExceptionE2(); 
       } 
      } 
     } 

請注意,可以用methodA1,methodA2調用許多方法。在那種情況下,有多次嘗試,趕上,最後會看起來醜陋..那麼有沒有其他方法可以做到這一點?

我需要將錯誤信息存儲在日誌文件中。在methodA1()中,每個標籤中的methodA2()...信息被驗證。我想要的是在日誌文件中包含所有錯誤信息。一旦拋出異常,它將生成日誌文件。所以我會錯過其他標籤的驗證信息。所以我們不可能最終採取行動。

回答

0

您可以使用與Java 8個lambda表達式一個循環:

interface RunnableE { 
    void run() throws Exception; 
} 

class Example { 

    public static void main(String[] args) { 
     List<RunnableE> methods = Arrays.asList(
       () -> methodA1(), 
       () -> methodA2(), 
       () -> methodA3() 
     ); 

     for (RunnableE method : methods) { 
      try { 
       method.run(); 
      } catch (Exception e) { 
       // log the exception 
      } 
     } 
    } 

    private static void methodA1() throws Exception { 
     System.out.println("A1"); 
    } 

    private static void methodA2() throws Exception { 
     System.out.println("A2"); 
    } 

    private static void methodA3() throws Exception { 
     System.out.println("A3"); 
    } 

} 

請注意,只有當方法拋出checked異常時需要使用接口。如果他們只拋出運行時異常,則可以使用java.lang.Runnable代替。

+0

由於不允許檢查異常,因此不能使用'Runnable'。請注意,OP正在拋出名爲'ExceptionE'的檢查異常,列在方法的'throws'子句中。 – Andreas

+0

@Andreas聲明'throws'子句並不意味着它是檢查異常,您也可以將它用於運行時異常:)無論如何,感謝您指出它,我已經更新了我的答案。 –

0

沒有其他辦法。如果每個方法都可以拋出異常,但是您仍想繼續執行其餘方法,則每個方法調用都必須位於其自己的try-catch塊中。

例子:

List<Exception> exceptions = new ArrayList<>(); 
try { 
    methodA1(); 
} catch (Exception e) { 
    exceptions.add(e); 
} 
try { 
    methodA2(); 
} catch (Exception e) { 
    exceptions.add(e); 
} 
try { 
    methodA3(); 
} catch (Exception e) { 
    exceptions.add(e); 
} 
if (! exceptions.isEmpty()) { 
    if (exceptions.size() == 1) 
     throw exceptions.get(0); 
    throw new CompoundException(exceptions); 
} 

當然,你必須自己實現CompoundException