Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8165147

Issue with type inference of generic exceptions in mapped optional

XMLWordPrintable

    • Icon: Bug Bug
    • Resolution: Cannot Reproduce
    • Icon: P4 P4
    • None
    • 8u102
    • tools
    • None
    • generic
    • generic

        When compiling the following class:

        import java.util.Optional;
        class Test {
        void test() {
            Optional<String> s = Optional.ofNullable("string");
            String res = s.map(st -> "non-null").orElseThrow(() -> {throw new NullPointerException("Gee, didn't see that coming!");});
        }
        }

        the compiler reports an error like this:

        error: unreported exception Throwable; must be caught or declared to be thrown
            String res = s.map(st -> "non-null").orElseThrow(() -> {throw new NullPointerException("Gee, didn't see that coming!");});

        Because of possible type inference, no compiler error should be reported.

        This bug can always be produced.

        You can work around this bug, by using an anonymous inner class with explicit generic type, i.e. something like:

        [...].orElseThrow(new Supplier< NullPointerException >() {
                    @Override
                    public NullPointerException get() {
                        throw new NullPointerException("Gee, didn't see that coming!");
                    }
                })

        Or by explicitly typing orElseThrow() like this:

        [...].<NullPointerException>orElseThrow(() -> {throw new NullPointerException("Gee, didn't see that coming!");});

              vromero Vicente Arturo Romero Zaldivar
              hschreiber Hendrik Schreiber
              Votes:
              0 Vote for this issue
              Watchers:
              2 Start watching this issue

                Created:
                Updated:
                Resolved: