Skip to content
Advertisement

What i should return if was an error creating a user

I have a method to create a user, this method check if the username exist and if the password is strong. If the creaton have an error i was returning a exception with a message, but i read this is not an exceptional situation so i don should to use an exception. what should I return to know if the user has been created, and if not, why?

public User(String username, String password) throws Exception {
    
    if (userController.usernameTaken(username)) {
        throw new Exception("Username already taken");
    }
    
    this.username = username;
    
    setPassword(password); //this method throw an exception if the password is not strong
}

Advertisement

Answer

It is absolutely correct to throw some exception here.

The expectation of someone calling new User("me", "mySecret") is that after that call, there is a legitimate, working User instance with the appropriate settings. There are situations where this is impossible (username taken, weak password, …), so that the constructor cannot fulfill its contract. That’s what exceptions are meant for.

And, as we’re talking about a constructor, there’s hardly any other option:

  • You can just create the User although it’s not functioning. This will create lots of problems later on, as there’s no way for your caller to see the invalidity of that instance.
  • You can include a boolean valid field in the User class with an isValid() accessor, and set that to true or false depending on the parameter validity. But forcing your caller to check for validity by calling that method reminds me of the bad old times with the C language in the 1980s.
  • So, exceptions are the way to go.

In your case, the calling software probably wants to deal with the different types of failure differently, e.g. by asking the user to supply either a different user name or a different password. You should make this easy for your caller by using two specific, different exception classes.

Advertisement