Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java equivalent to .NET System.InvalidOperationException

Tags:

java

exception

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

like image 398
Sergio Acosta Avatar asked Aug 01 '10 08:08

Sergio Acosta


People also ask

What is System InvalidOperationException?

InvalidOperationException is used in cases when the failure to invoke a method is caused by reasons other than invalid arguments. Typically, it is thrown when the state of an object cannot support the method call. For example, an InvalidOperationException exception is thrown by methods such as: IEnumerator.


1 Answers

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.

like image 56
Jon Skeet Avatar answered Sep 18 '22 17:09

Jon Skeet