2 ms·
In Java, the concept of exceptions is incompatible with the concept of parametrized types. During compilation, type parameters are erased. "T" becomes "Object"
by Viliam1234 8y ago
In 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.