Core java tutorial for beginners
A tutorial blog which explains different core concepts related to Java along with programming examples

January 12, 2016 Categories: Exception Handling. No Comments on User Defined Exceptions

In this article we will learn how to create user defined exceptions (own exceptions) and how to use them in Java programs.

Although Java provides several pre-defined exception classes, sometimes we might need to create our own exceptions which are also called as user-defined exceptions.

Steps for creating a user-defined exception:

  1. Create a class with your own class name (this acts the exception name)
  2. Extend the pre-defined class Exception
  3. Throw an object of the newly create exception

As an example for user-defined exception, I will create my own exception named NegativeException as follows:

Note that I am overriding the toString() method of the Exception class to provide meaningful description of my own exception.

Now, I can use my own exception NegativeException in Java programs as shown below:

Output of the above program is:

NegativeException: Value cannot be negative

From the above program you might have guessed the use of NegativeException. It notifies the user about negative values which are not allowed as input.

This how we can create and use our own exceptions in Java.

Note: Do you have a question on this article or have a suggestion to make this article better? You can ask or suggest us by filling in the below form. After commenting, your comment will be held for moderation and will be published in 24-48 hrs.

Leave a Reply

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

Scroll Up
Thank you for visiting startertutorials.com! If you like this website do share with your friends by clicking on the social icons available on the left hand side.

As the domain name is quite large to remember, use this short domain to visit this site. Short domain: stuts.me