3 ms·
I wonder why they didn't use generic exception type in their java.util.function classes. That would propagate checked exceptions statically. Something like
by vbezhenar 8y ago
I wonder why they didn't use generic exception type in their java.util.function classes. That would propagate checked exceptions statically.
Something like
@FunctionalInterface
interface Function<T, R, E extends Throwable> {
R apply(T t) throws E;
}
- swsieber 8y agoAh, that's because java generics don't work with exceptions.
- vbezhenar 8y agoWhat do you mean? They do work with exceptions.
- swsieber 8y agoAh, my mistake. I was thinking of generice type arguments for exception subclasses: https://www.mscharhag.com/java/java-exceptions-and-generic-types https://www.mscharhag.com/java/java-exceptions-and-generic-t... That also includes generic catch clauses and inner exception types of classes with type parameters.
- Viliam1234 8y agoIn Java, the concept of exceptions is incompatible with the concept of parametrized types. During compilation, type parameters are erased. "T" becomes "Object"; "T extends Something" becomes "Something"; assignment becomes type conversion. But at the end it works correctly. If you try to make something that wouldn't survive the type parameter erasure -- such as having two methods with the same name, one of which accepts "List<String>" and another accepts "List<Integer>" as their input -- it will be a compile-time error, because you can't have two methods with the same name and the same parameter "List". But imagine that you have a type "MyException" extending RuntimeException, and your code has "catch (MyException)". After compilation, this would become "catch (RuntimeException)", which is wrong, because it would also catch other RuntimeExceptions, and it is not supposed to. But if you make this construction a compile-time error, then... the whole thing becomes useless, because what's the point of having an exception type you cannot catch.
- vbezhenar 8y agoThe entire concept of checked exceptions is compile-time, because there's no checked exceptions in JVM. I don't really understand your argument. I'm not suggesting to catch exception of generic type, it won't be possible indeed, but it's not required either. You just need to tell compiler to pass "throws" via generic type. You can declare your map function with generic throws and compiler will respect that.
- vbezhenar 8y agoOn further thought I understood that streams usually are lazy and real exception would be thrown not at map, but later (probably in collect or similar method). So it would require to propagate that E generic parameter to almost every function (and Stream type signature). Also it won't work well with multiple checked exceptions. So yeah, not that easy.
- chopin 8y agoThis doesn't work if your function throws multiple checked exceptions.