3

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!

Forepick
  • 919
  • 2
  • 11
  • 31
  • http://stackoverflow.com/questions/5875414/why-cant-overriding-methods-throw-exceptions-broader-than-the-overriden-method – Codebender Oct 20 '15 at 08:46

2 Answers2

5

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

Eran
  • 387,369
  • 54
  • 702
  • 768
1

You can always throw an Exception derived from RuntimeException.

wero
  • 32,544
  • 3
  • 59
  • 84