From a good design/practice point of view, when should we create and use custom Java exception classes instead of the ones already predefined in Java?
In some applications I see almost custom exception classes created, they make an effort to always use native Java exceptions. On the other hand, there are some applications that define custom exceptions for (almost) everything.
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");