When you pass a callback in some form to another function, you often have to fullfil some interface to be able to pass such callback. That callback interface will often restrict you in what type of exceptions you can throw.
The most natural way for me would be that the called function would automatically rethrow (or ignore) the exceptions thrown by the callback. I.e. that it automatically inherits the list of exceptions it can throw from the callback. I.e. that the list of exceptions it can throw is generic.
Is something like possible already? If so, why isn't it used by Javas library yet?
If it is not possible yet, why not? It wouldn't have been complicated to include that in the language. And it would have made some things more clean (see above).
One example:
I just stumbled upon that Comparator.compare
cannot throw an exception (see here for a related question) and Collections.sort
(or other functions which use Comparator
) also does not.
It would make much more sense to me if the exceptions which Comparator.compare
can throw would be generic and Collections.sort
would throw just the same. This would solve my problem here in a much more natural and clean way.