Search code examples
javaexceptionlambdafunctional-interface

Java issue with Exception not being handled (functional interface with lambdas)


I really need some help. This is my functional interface:

/**
 * This class represents a filter.
 */
@FunctionalInterface
interface FileFilter {
    /**
     * This method gets a file path and filters it in some method.
     * @return a list of the remaining files after this filter.
     * @throws IOException
     */
    abstract boolean filter(Path path) throws IOException;
}

This is the lambda function that I've written:

    static FileFilter modeFilter(String value, boolean containsNo, Predicate<Path> pathMethod)
    throws IOException{
        if (value.equals(YES)) {
            if (containsNo) {
                return path -> !pathMethod.test(path);
            } else {
                return path -> pathMethod.test(path);
            }
        }

        if (containsNo) {
            return path -> pathMethod.test(path);
        }
        return path -> !pathMethod.test(path);
    }

I am giving the filter this parameters:

Filters.modeFilter(commandParts[1], containsNOT, x -> Files.isHidden(x))

The problem is that I get a compliation error in Files.isHidden that says that there is an Excpetion not handled - IOExeption.

I made sure that the method that calls modeFilter throws IOExeption, so this is not the problem. How do I solve this?

Thank you.


Solution

  • Your method takes a Predicate<Path> as argument.

    The signature of the Predicate function is

    boolean test(T)
    

    But the signature of Files.isHidden is

    boolean isHidden(Path path) throws IOException
    

    So they don't match: a predicate is not supposed to throw an IOException, but Files.isHidden() can.

    Solution: pass a FileFilter as argument, rather than a Predicate<File>, since the only reason FileFilter exists is precisely so that it can throw an IOException, unlike a Predicate.

    Note that the modeFilter method has no reason to throw an IOException: all it does is creating a FileFilter. It never calls it. So it can't possibly throw an IOException.