What are different types of user exceptions in Java Programming

Follow by Email
Facebook0
Facebook
Google+
https://codingsec.net/2017/05/different-types-user-exceptions-java-programming/

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.

A 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.

Follow by Email
Facebook0
Facebook
Google+
https://codingsec.net/2017/05/different-types-user-exceptions-java-programming/

One Response

  1. daisy 2017-05-11 Reply

Add a Comment

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

Like the article? please consider sharing it. Thank you

Advertisment ad adsense adlogger