Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exception to throw when pre-requisite method was not called?

Tags:

java

exception

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?

like image 611
Amir Rachum Avatar asked Jul 02 '11 14:07

Amir Rachum


1 Answers

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.

like image 179
Peter Lawrey Avatar answered Nov 14 '22 23:11

Peter Lawrey