The direct answer is because Comparator.compare
s interface is specified as such that it does not throw exceptions. But why is that?
Or to put it different: My Comparator
must depend on a function which can throw an exception. In theory, that should not happen. But if it happens, I want that it breaks out of the whole function where I am using that Comparator
(in Collections.sort
). I.e. I want that it just behaves as if an unhandled exception has occurred.
It seems that this is not possible in an obvious natural way (because if the interface says that it cannot throw an exception, it can't).
How would I solve this? With an ugly try/catch and print out the exception and hope that I recognize it? That seems to be a quite ugly way.
You can always throw a RuntimeException, or one derived from it, even from a method not explicitly declaring itself to throw exceptions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With