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

Issue with type inference of generic exceptions in mapped optional

    XMLWordPrintable

    Details

    • Type: Bug
    • Status: Resolved
    • Priority: P4
    • Resolution: Cannot Reproduce
    • Affects Version/s: 8u102
    • Fix Version/s: None
    • Component/s: tools
    • Labels:
      None
    • Subcomponent:
    • CPU:
      generic
    • OS:
      generic

      Backports

        Description

        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!");});

          Attachments

            Issue Links

              Activity

                People

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

                  Dates

                  Created:
                  Updated:
                  Resolved: