gpt4 book ai didi

java - 从 Java 类的重写方法中抛出异常

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:42:36 25 4
gpt4 key购买 nike

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

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

最好的解决方案是什么?

谢谢!

最佳答案

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

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

来自 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

关于java - 从 Java 类的重写方法中抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33231865/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com