User-defined Exceptions

User-defined Exceptions

Java provides many built-in exception but at many times built-in exceptions are not able to describe a certain situation. In such cases, like the built-in exception, the programmer can also create his own exception which are called user-defined exception.

Before going ahead one must be aware about basics of Exception Handling, which has been explained here.

Now let’s see how we can create User Defined exception-


1). The user should create an exception class as a subclass to Exception class. Since all exception are subclasses of Exception class, the user should also make his class a subclass to it.

2). The user can write a default constructor in his own exception class. He can use it, in case he does not want to store any exception details. If user does not want to store any exception details. If the user does not want to create any empty object to his exception class, he can eliminate writing the default constructor.

3). The user can create a parametrized constructor with a String as a parameter. He can use this to store exception details. He can pull super class (Exception) constructor from this and send the string there.

4). When the user wants to raise his own exception, he should create an object to his exception class and throw it using throw clause as –




Stay tuned for more updates !

Leave a Reply

Your email address will not be published. Required fields are marked *