3 ms·
Fun fact: you can actually parameterize functions and types over exception types in Java, <T extends Throwable> ... throws T will type check as expected. Of co
by PhilipRoman 3y ago
Fun fact: you can actually parameterize functions and types over exception types in Java, <T extends Throwable> ... throws T will type check as expected.
Of course, if you solve a problem using generics, you will now have 2 problems instead of 1...
- Thiez 3y agoAnd stuff like the Stream api does not use these generics, so you end up wrapping exceptions in RuntimeException anyway, which... again defeats the point of checked exceptions.
- Groxx 3y agoI have never tried that, thanks! Does it work for a variable list of things, or would supporting two different checked exceptions require two generic params? If it's one per param I think that's neat but probably limited in use to "your exception can contain a generic value", like `throw NewInsertFailedException(value)`.
- PhilipRoman 3y agoI think you might be able to trick the type checker to accept union types, but I'm not sure. I know intersection types are possible, but they are not really useful for exceptions. Regarding practicality - I've used this feature when implementing a visitor class API, so it definitely has some use cases. The biggest problem is that all it takes is a single method in the chain which does not support this pattern (think java.util.stream). For internal code it's pretty easy to decorate all functions that take callback lambdas, etc.