1

The code below doesn't compile. I get Unhandled exception type Throwable.

public static void main(final String[] args) throws Exception {
    MyResponse myResponse = new MyResponse();
    myResponse.getObjects().stream().findFirst().orElseThrow(() -> SOME_EXCEPTION);
 }

However if I put the type object then it works fine :

MyResponse<Object>  myResponse = new MyResponse<>();

And MyResponse class has a list of objects :

private List<T> objects;

What could be the issue?

fastcodejava
  • 39,895
  • 28
  • 133
  • 186
  • 1
    I think it has a little in common with raw types, reopened it. – Andrew Tobilko Aug 09 '18 at 15:38
  • 1
    @AndrewTobilko Have you read that Q&A? This question is answered under the section [*A raw type is the erasure of that type*](https://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it). – Radiodef Aug 09 '18 at 15:42
  • 3
    It does. `() -> SOME_EXCEPTION` is a `Supplier`. Once you use raw types, you live in a pre-generics world where genrics don't exist. So the Supplier basically becomes a Supplier. So you need to catch, because the compiler has no way to know that the exception thrown by orElseThrow is a runtime exception. Don't use raw types. – JB Nizet Aug 09 '18 at 15:42
  • @JBNizet you're absolutely right, but eliminating raw types doesn't help if you provide a supplier of a checked exception. It guarantees only that unchecked exception suppliers won't cause a compilation error – Andrew Tobilko Aug 09 '18 at 15:47
  • Of course, but that's not what the OP is doing, otherwise the code wouldn't compile when he uses `MyResponse`, i.e. when he doesn't use a raw type anymore. – JB Nizet Aug 09 '18 at 15:49
  • @JBNizet, makes sense to me now, agreed to close :) – Andrew Tobilko Aug 09 '18 at 15:50

0 Answers0