81

I am not as familiar with Java's exception packages as with those of .NET. I'm in a situation where, if programming in C#, I would throw a System.InvalidOperationException.

Before creating my own java.lang.RuntimeException subclass, I need to know if there is a similar exception type I should throw in Java.

The exact scenario is:

My class is a value object that provides an int intValue() method, returning an int. However, in some situations, the current value cannot be provided as an int, so this class also provides a boolean isInteger() to allow API users to know when intValue() can be safely invoked.

If a caller calls intValue() when isInteger() is false, an exception should be thrown.

And the question is: What type of exception?

I know that this question might not have a correct answer, but considering that I don't have lots of experience designing Java APIs, I want to know from other Java developers what they would expect to be thrown in this scenario.

thanks

Stephen Kennedy
  • 20,585
  • 22
  • 95
  • 108
Sergio Acosta
  • 11,418
  • 12
  • 62
  • 91
  • possible duplicate of [Is there a Java equivalent of C#'s InvalidOperationException?](http://stackoverflow.com/questions/3165701/is-there-a-java-equivalent-of-cs-invalidoperationexception) – Carl Jun 11 '13 at 14:02

1 Answers1

92

Throw an IllegalStateException:

Signals that a method has been invoked at an illegal or inappropriate time. In other words, the Java environment or Java application is not in an appropriate state for the requested operation.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 14
    `IllegalStateException` is definitely correct for the specific case that was asked about. Note that in some situations I believe it may be more appropriate to throw an `UnsupportedOperationException`. For example if an `Iterator` does not support the `remove` method. – csauve Jul 10 '15 at 21:55