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.
Basically, Java custom exceptions are used to customize the exception according to user need. Consider the example 1 in which InvalidAgeException class extends the Exception class. Using the custom exception, we can have your own exception and message. Here, we have passed a string to the constructor of superclass i.e.
Steps to create a Custom Exception with an ExampleCreate one local variable message to store the exception message locally in the class object. We are passing a string argument to the constructor of the custom exception object. The constructor set the argument string to the private string message.
You can create your own exceptions in Java. All exceptions must be a child of Throwable. If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class. If you want to write a runtime exception, you need to extend the RuntimeException class.
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");
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