IllegalStateException vs IllegalArgumentException in Java
In Java, IllegalStateException
and IllegalArgumentException
are both subclasses of the RuntimeException
class, and they are used to indicate that a method has been invoked with an illegal or inappropriate argument or state. However, they are used to indicate slightly different things:
IllegalStateException
is thrown when a method has been invoked on an object that is in an illegal or inappropriate state. For example, if a method that is only supposed to be called once has been called multiple times, anIllegalStateException
might be thrown.IllegalArgumentException
is thrown when a method has been invoked with an illegal or inappropriate argument. For example, if a method that expects a positive number is passed a negative number, anIllegalArgumentException
might be thrown.
Here's an example of how they can be used:
public class MyClass {
private boolean isInitialized = false;
public void initialize() {
isInitialized = true;
}
public void doSomething() {
if (!isInitialized) {
throw new IllegalStateException("MyClass has not been initialized.");
}
// do something
}
public void setValue(int value) {
if (value < 0) {
throw new IllegalArgumentException("value must be non-negative.");
}
// set the value
}
}
In this example, the initialize
method sets the state of the object, and the doSomething
method checks the state before doing something. If the state is not initialized, it throws an IllegalStateException. On the other hand, setValue
method checks the parameter passed to it before setting it, and if the value is less than 0, it throws an IllegalArgumentException.
In summary, IllegalStateException
is used to indicate that a method has been invoked on an object that is in an illegal or inappropriate state, while IllegalArgumentException
is used to indicate that a method has been invoked with an illegal or inappropriate argument.