Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to implement a general try catch method in java using lambda expressions?

Tags:

java

java-8

I've been trying to create a general trycatch method like this:

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

However I get an unhandled exception if I try to use it like this:

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

How can I implement this so that the compiler knows that tryCatchAndLog will handle the Exception?

like image 254
EJS Avatar asked Jun 10 '26 09:06

EJS


2 Answers

Try this :

@FunctionalInterface
interface RunnableWithEx {

    void run() throws Throwable;
}

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

Then this code compiles:

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

    tryCatchAndLog(this::throwX);

}

public void throwX() throws Exception {
    throw new Exception();
}
like image 66
Sxilderik Avatar answered Jun 11 '26 22:06

Sxilderik


Change Runnable to custom interface that is declared to throw Exception:

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);
        }
    }

}
like image 25
Andrii Abramov Avatar answered Jun 11 '26 22:06

Andrii Abramov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!