从 Java class 的覆盖方法中抛出异常

Throw an exception from an overridden method of a Java class

我想扩展 Java 的 HashMap<K, V> class。我覆盖了 put(...) 方法,我想在某些情况下抛出异常。

由于基础 class 的 put 方法没有抛出异常,我得到一个编译器错误。

最好的解决方案是什么?

谢谢!

您始终可以抛出从 RuntimeException 派生的异常。

您可以在子 class 中创建一个不覆盖 put 的方法,但在必要时调用原始 put()。这样的方法将被允许抛出您希望的任何异常。

或者您可以抛出 put 已经可能抛出的未经检查的异常之一(UnsupportedOperationExceptionClassCastExceptionNullPointerExceptionIllegalArgumentException)或任何其他未经检查的异常(尽管不太推荐这样做,因为它们不会记录在 Map 界面中)。

来自 Map::put Javadoc :

Throws:

UnsupportedOperationException - if the put operation is not supported by this map
ClassCastException - if the class of the specified key or value prevents it from being stored in this map
NullPointerException - if the specified key or value is null and this map does not permit null keys or values
IllegalArgumentException - if some property of the specified key or value prevents it from being stored in this map