Forepick
Forepick

Reputation: 937

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!

Upvotes: 3

Views: 1054

Answers (2)

Eran
Eran

Reputation: 393866

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

Upvotes: 5

wero
wero

Reputation: 33000

You can always throw an Exception derived from RuntimeException.

Upvotes: 1

Related Questions