Tuesday 30 September 2014

How to create a user defined exception in Java?

An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program. When an error occurs within a method (member function), the method creates an object of the error/exception and hands it off to the runtime system.

Java provides better exception handling mechanism for its programmers. It simplifies the exception handling process and gives a try .... catch ... finally stucture to handle the exception.


Many exceptions that may occur in general are defined  as various exception classes and they are available  with standard java package.

However there may be cases, where project specific exceptions are to be handled. These type of exceptions are called user-defined exceptions.

Here we will check, how a user-defined exception is created and used. All user-defined exceptions should inherit the java.lang.Exception class.

In our example InvalidAgeException is a class derived from the Exception class and it overrides the toString() function to return a custom error message.

From the evaluate() function, which is defined in the ExceptionTest class, the age given is evaluated and new instance of  InvalidAgeException is thrown, if needed. The exception object thrown by the evaluate() function is caught from the main function and reported to the user.


Source Code

InvalidAgeException.java

class InvalidAgeException extends Exception {
        private String strError;
      
       /* Default constructor */
        public InvalidAgeException () {
                this.strError = "Invalid Age";
        }
      
      /* Overloaded constructor */
        public InvalidAgeException (String strError) {
                this.strError = strError;

        }
       /* Overrides toString() function */
        public String toString() {
                return this.strError;
        }
}

ExceptionTest.java
 class ExceptionTest {
        public static void main(String a[]) {
                int age=0;

                try {
                   age = Integer.parseInt(a[0]);     // Reads value through command line argument
                   evaluate(age); // Invokes the evaluate function
                }
             
                /* Triggers when command line argument is not passed */
                catch (ArrayIndexOutOfBoundsException e) {
                        System.out.println("Too few parameters!");
                }
            
              /* Triggers when command line argument given is not an integer number  */
                catch (NumberFormatException e) {
                        System.out.println("Parameter is not an integer number");
                }

              /* Triggers when the age given as argument is not within the allowed range (18 - 65) */
                catch (InvalidAgeException e) {
                        System.out.println(e.toString());
                }
             
               /* Triggers when any other exception is occurred */
                catch (Exception e) {
                        System.out.println(e.toString());
                }

        }

        public static void evaluate(int age) throws InvalidAgeException {
                if (age<0)
                        throw new InvalidAgeException("It is a negative value");
                else if (age<18) {
                        throw new InvalidAgeException("It is a minor");
                }
                else if (age<65) {
                        System.out.println("Age is within the valid range.");  
                }
                else {
                        throw new InvalidAgeException("It is a senior citizen");
                }
                       
        }
}

Output
D:\java\exception>java ExceptionTest -1
It is a negative value

D:\java\exception>java ExceptionTest 15
It is a minor

D:\java\exception>java ExceptionTest 19
Age is within the valid range.

D:\java\exception>java ExceptionTest 68
It is a senior citizen

How to test the program on your computer? 

1. Create InvalidAgeException.java file and copy the source code in the section 1.
2. Create ExceptionTest.java and copy the source code in the section 2.
3. Compile the exception class by using the command javac InvalidAgeException.java
4. Compile the program by using the command javac ExceptionTest.java
5. Run the program by using the command java ExceptionTest <value for age>

This program takes the value for age variable through command line argument. So you have to pass the value for age variable like this ExceptionTest 18. Here 18 is the age that you are passing to the program.



No comments:

Post a Comment