3 ms·
I can't write a method like this: public <T> higherOrderFunction(Function<T> f) throws whatever f throws { } I can write a method that takes in a function obj
by sreque 6y ago
I can't write a method like this:
public <T> higherOrderFunction(Function<T> f) throws whatever f throws {
}
I can write a method that takes in a function object that throws zero checked exceptions. I can write a method that takes in a function that throws exactly one type of checked exception. I can write a method that takes in a function object that can throw two types of checked exceptions. And so on. But this involves lots of copy-pasting, which is the opposite of abstracting.
Checked exceptions are not first-class citizens in the language (see https://en.wikipedia.org/wiki/First-class_citizen https://en.wikipedia.org/wiki/First-class_citizen). Unlike return values, I can't, for instance, in the general case assign the possible checked exception thrown by a method to a variable without losing type information. To do so would require sum types, a feature which most popular languages don't have.
On the other hand, if I create a class like IO<T>, which represents a possible return value of T or an IOException, then that is first class in the language and I can do anything with it that I can do with any other first-class value in the language.
- Nursie 6y agoSo you effectively want - class ThrowingFunction<T, R>{ public T execute() throws R; } public <T, R> higherOrderFunction(ThrowingFunction<T,R> f) throws R { } Honestly I have no idea if such a construct is possible. You can write a method that throws a superclass of exceptions. At this point though I'm going to say I also don't see the utility. By the time we're getting so abstract we're also getting into code that can be quite hard to reason about and debug. Exceptions are first class in java AFAICT, they're just objects. You can store anything in them and pass them around freely.