Java:为什么我不能在比较器中抛出异常? [英] Java: why can't I throw an exception in Comparator?
问题描述
直接的答案是因为 Comparator.compare
s接口被指定为不会抛出异常。但是为什么会这样呢?
The direct answer is because Comparator.compare
s interface is specified as such that it does not throw exceptions. But why is that?
或者说它不同:我的比较器
必须依赖于一个可以抛出例外。在理论上,这不应该发生。但是如果发生这种情况,我希望它能够在整个函数中使用 Comparator
( Collections.sort
)。即我想要它就像一个未处理的异常发生一样。
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).
我该如何解决?有一个丑陋的try / catch和打印异常,希望我认识到它?这似乎是一个非常丑的方式。
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.
推荐答案
在这种情况下,我会重新推出一个 AssertionError
,因为你假定不能提出异常。不要忘记使用 initCause()
方法传播信息( AssertionError
没有构造函数接受 Throwable
)
In this case, I would rethrow an AssertionError
since you assume that the exception can't be raised. Don't forget to use the initCause()
method to propagate the information (AssertionError
doesn't have a constructor accepting a Throwable
)
这篇关于Java:为什么我不能在比较器中抛出异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!