2017-01-03 42 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