2016-12-23 13 views
2

私はこのような一般的なtrycatchメソッドを作成しようとしてきた:ラムダ式を使ってjavaで一般的なtry catchメソッドを実装することは可能ですか?

tryCatchAndLog(() -> { 
    methodThatThrowsException(); 
}); 

どのように私はこれを実装することができます:私はこのようにそれを使用しようと、私は未処理の例外を取得しかし

public static void tryCatchAndLog(Runnable tryThis) { 
    try { 
     tryThis.run(); 
    } catch (Throwable throwable) { 
     Log.Write(throwable); 
    } 
} 

をコンパイラはtryCatchAndLogがExceptionを処理することを認識しますか?例外をスローするように宣言されているカスタムインターフェイスへ

答えて

4

はこれを試してみてください:

@FunctionalInterface 
interface RunnableWithEx { 

    void run() throws Throwable; 
} 

public static void tryCatchAndLog(final RunnableWithEx tryThis) { 
    try { 
     tryThis.run(); 
    } catch (final Throwable throwable) { 
     throwable.printStackTrace(); 
    } 
} 

次に、このコードはコンパイルされます。

public void t() { 
    tryCatchAndLog(() -> { 
     throw new NullPointerException(); 
    }); 

    tryCatchAndLog(this::throwX); 

} 

public void throwX() throws Exception { 
    throw new Exception(); 
} 
+2

私はThrowableを捕まえないように助言します。あなたがそうしないと正当な理由がない限り、「例外」を捕まえる。 – Sxilderik

4

変更したRunnableに:

public class Example { 

    @FunctionalInterface 
    interface CheckedRunnable { 
     void run() throws Exception; 
    } 

    public static void main(String[] args) { 
     tryCatchAndLog(() -> methodThatThrowsException()); 
     // or using method reference 
     tryCatchAndLog(Example::methodThatThrowsException); 
    } 

    public static void methodThatThrowsException() throws Exception { 
     throw new Exception(); 
    } 

    public static void tryCatchAndLog(CheckedRunnable codeBlock){ 
     try { 
      codeBlock.run(); 
     } catch (Exception e) { 
      Log.Write(e); 
     } 
    } 

} 
+0

まあ、我々は同じを入力します同時に答えてください:) – Sxilderik

+1

はい。あなたのために+1: –

関連する問題