Lazy Diary @ Hatena Blog

PowerShell / Java / miscellaneous things about software development, Tips & Gochas. CC BY-SA 4.0/Apache License 2.0

You cannot wrap checked exceptions with lambda in Java

Context

  • You can use lambda as lazy evaluation syntax in Java.

Problem

You can wrap RuntimeException with lambda like (it shows "omit exception"):

import java.util.function.Supplier;

public class OmitRuntimeException {
    public static void main(String[] args) {
        OmitRuntimeException o = new OmitRuntimeException();
        o.wrapLambda(() -> o.throwException());
    }

    public void wrapLambda(Supplier<String> msg) {
        try {
            System.out.println(msg.get());
        } catch (Exception e) {
            System.out.println("omit exception");
        }
    }

    public String throwException() throws RuntimeException {
        if (true) {
            throw new RuntimeException();
        }
        return "";
    }
}

But you cannot wrap ordinal Exception with lambda like:

import java.util.function.Supplier;

public class OmitException {
    public static void main(String[] args) {
        OmitException o = new OmitException();
        o.wrapLambda(() -> o.throwException());
    }

    public void wrapLambda(Supplier<String> msg) {
        try {
            System.out.println(msg.get());
        } catch (Exception e) {
            System.out.println("omit exception");
        }
    }

    public String throwException() throws Exception {
        if (true) {
            throw new Exception();
        }
        return "";
    }
}

And you will get a compile error:

$ LANG=C javac OmitException.java 
OmitException.java:6: error: unreported exception Exception; must be caught or declared to be thrown
        o.wrapLambda(() -> o.throwException());
                                           ^
1 error

Solution:

Use RuntimeException, or wrap the function that thows checked exceptions with another function.