Custom Exception in Java

In earlier tutorials, we have seen how to do Exception Handling in Java, throw an exception, how to use finally block, throws keyword etc.. In this tutorial we will learn about how  to create Custom Exception in Java.

Inside the java.lang package, Java defines several built-in exception classes for ex. IOException, NullPointerException etc. Although Java’s built-in exceptions handle most common errors, you will probably want to create your own exception types to handle situations specific to your applications.

To create your own Custom Exception in Java, you just define a subclass of Exception. Since Exception class inherits Throwable class, the custom exception class that you create will have methods defined by Throwable class available to them. You may override one or more of these methods in the custom exception classes that you create.

Example of Custom Exception:

Let’s create the Custom Exception class.

Here we have created BusinessException class which extends Exception class. BusinessException class has one constructor which accepts the error message that will be shown in case of any exception.

Let’s create class to demonstrate the BusinessException class.


Let’s run the demo class and check the output.

In this program, we have created our own custom exception BusinessException. If you observe the output, the program has thrown the custom exception BusinessException that we have created and printed the custom message that we have passed to the BusinessException.

Related posts

Leave a Comment