views:

54

answers:

3

I have a method that takes an enum as a parameter and returns some information dependent on that parameter. However, that enum contains some values which should not be handled, and should raise an error condition. Currently the method throws an IllegalArgumentException but I would like this to be a checked exception to force callers to catch it (and return gracefully, logging an error). Is there something suitable or should I create my own Exception subclass?

I'm open to other patterns as well. A reasonable reaction would be that all values of the enum should be handled, but that isn't the case. When a new value is added to the enum, I want to make sure that this method does the right thing - alerting a human is preferable to using some default return value in this case.

Thanks for any advice.

+2  A: 

The questions are:

  • how "normal" are cases when the method is called with an unsuitable enum parameter?
  • can you handle these cases gracefully and then continue processing?

From what you describe, it is not "normal" (happens only when a new enum value is added and the method is not updated properly - i.e. when a bug was introduced). So to me this sounds more like a case for RuntimeException (i.e. unchecked). Callers of this method can still catch an unchecked exception if they really want to, but they are not forced to.

OTOH I would try to eliminate the case you describe, by moving the data your method is returning right inside the enum. This way whenever a new enum value is added, there is no way the relevant data could be forgotten.

If you are interested, you may want to check out this tutorial.

Péter Török
A: 

You can continue to throw the IllegalArgumentException and log an error message. In this scenario it will be effectively the same as throwing a checked exception and forcing the caller to handle it.

saugata
+1  A: 

You can certainly create a checked exception of your own (such as UnhandledEnumType), or you could catch and handle the IllegalArgumentException. It sounds a little fishy that only some values of the enum should be handled. One of the purposes of an enum is to bind values to a certain set of values, and I would expect all to be handled. If you're worried about new ones being added, you should have a test that tests that all values are properly handled (by using the values() method of the enum to ensure they are all tested).

Jeff Storey