0

I have a bunch of methods, with similar signatures, compatible with Function, they each declare throws InterruptedException, and I put them in a list and select one by its index and call its apply().

Except that I get a compiler error where the method is named to put in the list:

        final List<Function<Set<BookIdentifier>, Set<Status>>>
                submitters = List.of(
                        this::submitIndividuallySynchronously, // these are the method references
                        this::submitInBulkSynchronously,       // all 4 of them have an error message
                        this::submitIndividuallyAsynchronously,
                        this::submitInBulkAsynchronously);
        final var submitter =
                submitters.get((isIndividual() ? 0 : 1) + (isSynchronous() ? 0 : 2));

and writing a try/catch later

       try {
            result = submitter.apply(work.todo);
        } catch (final InterruptedException ex) {
            // do something here
        }

where the method reference is used (called) doesn't help.

The error from javac (SDK 17.0.5) is

error: incompatible thrown types InterruptedException in functional expression

(IntelliJ gives different errors: Each method reference has an error Unhandled exception: java.lang.InterruptedException and the later catch block has an error Exception 'java.lang.InterruptedException' is never thrown in the corresponding try block.)

So how can I name these method references in one place and call them in another?

  • Besides the obvious which is to surround the naming of them with a useless try/catch?
  • That it's an InterruptedException is not the issue, just needs to be any checked exception
davidbak
  • 5,775
  • 3
  • 34
  • 50
  • Just figured out the answer: Declare my own `@FunctionalInterface` where the `apply` method declares `throws Exception`. Now, question for community: Is this question sufficiently useful that it should be answered for future inquirers, or should I just delete it? – davidbak Jul 05 '23 at 23:46
  • 1
    This question has been asked before in many forms, so it may not provide much value to the site. Based on that alone, I would delete it. But you also worded your question in a relatively unique way, from what I can tell. Taking that into account, I would actually leave the question up so that others who word the question similarly are directed to the duplicate. – Slaw Jul 06 '23 at 00:24
  • 1
    Note there are libraries like https://github.com/pivovarit/throwing-function out there. – Slaw Jul 06 '23 at 00:28

0 Answers0