简体   繁体   中英

Throw an exception from an overridden method of a Java class

I want to extend Java's HashMap<K, V> class. I override the put(...) method and I want to throw an exception in some cases.

Since the base class's put method doesn't throw an exception, I get a compiler error.

What is the best solution for this?

Thanks!

You can create in your sub-class a method that doesn't override put , but calls the original put() if necessary. Such method will be allowed to throw any exception you wish.

Or you can throw one of the unchecked exceptions that put already may throw ( UnsupportedOperationException , ClassCastException , NullPointerException , IllegalArgumentException ) or any other unchecked exceptions (though that would be less recommended, since they won't be documented in the Map interface).

From 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM