Java

What are different types of user exceptions in Java Programming3 min read

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.

try block can be followed by multiple catch blocks to catch different types of exceptions in the code. Let’s look at a Java program which uses multiple catch blocks:

Output of the above program when z is given the value 2 by the user is:

z = 5
java.lang.ArrayIndexOutOfBoundsException: 4
Outside try-catch block

Output of the above program when z is given the value 0 by the user is:

java.lang.ArithmeticException: / by zero
Outside try-catch block

When using multiple catch blocks care should be taken that the order of exception classes must be from sub classes to the super class Exception. For example if the above program is modified as follows:

The above program when compiled will generate errors as the second and third catch blocks are non-reachable. To eliminate errors place the Exceptioncatch block as the last catch block.

Take your time to comment on this article.

Leave a Comment