Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: why can't I throw an exception in Comparator?

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.

like image 395
Albert Avatar asked Sep 30 '10 16:09

Albert


1 Answers

You can always throw a RuntimeException, or one derived from it, even from a method not explicitly declaring itself to throw exceptions.

like image 152
bramp Avatar answered Sep 22 '22 11:09

bramp