I have a method getUser
which retrieves a user from a database. The method demands that you verify that the user actually exists (via the userExists(String username)
method.
If the getUser
method is invoked and the user does not exist, I want to throw an unchecked exception, but which exception is the most appropriate here? I thought about IllegalArgumentException
, but it doesn't feel completely right, as certain inputs may be okay in some cases, but not others - they are not strictly "illegal". Any suggestions?
To me IllegalArgumentException means the argument is illegal and would always to illegal. Th exception I would use is IllegalStateException to say the state of the object to check the user is not valid.
However you may have an exception which is specific enough you could create your own.
public class UsernameNotCheckedException extends IllegalStateException {
public UsernameNotCheckedException(String message) {
super(message);
}
}
This may make debugging things easier.
A NumberFormatException
is a subclass of IllegalArgumentException
. Ifyou try to parse the number 12QW4
it will give you a NumberFormatException
and there is nothing you can do to make this a valid argument later. i.e. it has nothing to do with the state of anything.
The Javadoc for IllegalStateException
states.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With