User defined exception in java

User defined exception in java can be created by extending any predefined exception. User defined exception in java are also called Custom Exceptions. In java if we are developing an application and get some requirement to instruct the user who is going to use our class about the problem occurred while executing the statement.

To define user defined exception in java we can follow the below steps:-

  • Define a java class by extending any predefined exception but it is recommended to extend either java.lang.Exception or java.lang.RuntimeException. If we are extending the java.lang.Exception then our custom exception will be checked exception and if we are extending the java.lang.RuntimeException then our custom exception will be unchecked exception.
  • If we want to store some data then we can define some variable and to initialize the variable we can define the constructor.
  • To initialize the message for the exception we can we can invoke the super constructor with the string parameter.
  • We can override the method inherited from super class.

Example of user defined exception in java:-

output:-
User defined exception in java

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.