The direct answer is because Comparator.compares 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.
In this case, I would rethrow an
AssertionErrorsince you assume that the exception can’t be raised. Don’t forget to use theinitCause()method to propagate the information (AssertionErrordoesn’t have a constructor accepting aThrowable)