Learn Java

Custom Exceptions in Java

Java exceptions cover a lot of standard exceptions we have to deal with in programming. However, sometimes we might need to create them ourselves. One of the main reasons for this is to handle logical exceptions which are specific to your program. Imagine you are implementing a client-server application. The server processes user information and validates its correctness, or throws an exception. An essential condition for the server to work properly is that it should validate all the fields with user data and not stop at the first incorrect one. If some fields turn out to be incorrect, we want to receive a detailed report about what went wrong. In this case, a standard exception like IllegalArgumentException will not be enough for us, which means it's time to create a custom exception.

How to create and throw a custom exception

To create a custom exception you need to extend the Exception (checked) or RuntimeException (unchecked ) classes.

Here is an example:

public class MyAppException extends Exception {

    public MyAppException(String msg) {
        super(msg);
    }

    public MyAppException(Exception cause) {
        super(cause);
    }
}

In the example above, a new class of exceptions is declared. It is a checked exception because it extends the Exception class. The declared class has two constructors for creating instances, and they call the corresponding constructor of the base class.

Now, we can throw an instance of the class:

public static void someMethod() throws MyAppException {
    throw new MyAppException("Something bad");
}

Now let's learn some rules of creating custom exception class.

Best practices for custom exceptions

First things first, make sure that your application will benefit from creating a custom type of exception. Otherwise, use Java's built-in exceptions.

Secondly, follow the naming convention — end the class name with “Exception”, for example, MyAppException. By giving exceptions meaningful names, you improve the clarity of your code.

Also, provide the constructor that sets a cause in case your program catches a standard exception before throwing a custom one.

For example, let's look at the code snippet below. Here we capture the root cause of the exception with the Throwable argument, which is passed to the parent class constructor.

public class CustomException extends Exception {

   public CustomException(String message, Throwable cause) {

       super(message, cause);

   }

}

Is creating a custom exception always a good idea? Although the custom exception feature greatly enhances the error handling mechanism, its use is not always justified. We advise you to use standard exceptions whenever possible for a number of reasons, such as:

  • Standard exceptions are widely known by other programmers. One can understand the type of problem just by looking at the name of the exception.
  • By opting for a standard built-in exception, you follow the reusability principle. It makes your code clearer for the application users.

Conclusion

Custom exceptions are a great tool for handling inconsistencies in your program. In this topic, we learned how to create and throw them, along with some best practices to follow. However, we highly recommend creating a custom exception only when it is justified. Standard Java built-in exceptions are often a safer choice which is no less efficient.

Create a free account to access the full topic

“It has all the necessary theory, lots of practice, and projects of different levels. I haven't skipped any of the 3000+ coding exercises.”
Andrei Maftei
Hyperskill Graduate