When should we create our own Java exception classes? [closed]

From Best Practices for Exception Handling:

Try not to create new custom exceptions if they do not have useful information for client code.

What is wrong with the following code?

public class DuplicateUsernameException extends Exception {}

It is not giving any useful information to the client code, other than an indicative exception name. Do not forget that Java Exception classes are like other classes, wherein you can add methods that you think the client code will invoke to get more information.

We could add useful methods to DuplicateUsernameException, such as:

public class DuplicateUsernameException
    extends Exception {
    public DuplicateUsernameException 
        (String username){....}
    public String requestedUsername(){...}
    public String[] availableNames(){...}
}

The new version provides two useful methods: requestedUsername(), which returns the requested name, and availableNames(), which returns an array of available usernames similar to the one requested. The client could use these methods to inform that the requested username is not available and that other usernames are available. But if you are not going to add extra information, then just throw a standard exception:

throw new IllegalArgumentException("Username already taken");

Leave a Comment