开发者

Checked equivalent to IllegalArgumentException?

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 grace开发者_如何学JAVAfully, 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.


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).


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.


How about InstantiationException? Thrown when an application tries to create an instance of a class using the newInstance method in class Class, but the specified class object cannot be instantiated. The instantiation can fail for a variety of reasons including but not limited to: the class object represents an abstract class, an interface, an array class, a primitive type, or void the class has no nullary constructor

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜