Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
170 views
in Technique[技术] by (71.8m points)

java - Java8 Lambda Function assignment with exception


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think your problem is NotFoundException is a checked exception. Checked Exceptions (not RuntimeException subclasses) can not be thrown in a lambda. A workaround is to catch it and rethrown inside a RuntimeException as its cause.

Eg:

Function<Long, ShoppingCart> func = e -> {
        try {
            return fetchCart(e);
        } catch (NotFoundException ex) {
            RuntimeException re = new RuntimeException();
             re.initCause(ex);
             throw re;
        }
        return null;
    };

Then, when you will catch the runtimeException, you will have to handle its cause.

try {
    /// call func here
} catch(Exception e) {
    ((NotFoundException)e.getCause()).printStackTrace();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...