Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

How to Create User Defined Exceptions in Java ?.

In this section of blog, we will be looking into more depth about Exception handling. In this section we will see how to create user defined exceptions in Java ?. The Java API provides several Exception classes which are adequate for most purposes. However, in some cases, we may encounter a situation which cannot be described by standard exception types. For example, suppose we are accepting the birthdate of the user. If the user enters month as 15, we may want to treat it as an InvalidMonthException. For such cases, we may need to define our own exception types.

A user defined exception class must extend Exception. The syntax is given below:

Syntax: 

class UserDefinedException extends Exception
{
  // code
}

To give a default text message regarding the exception, simply override the toString() method. This class can also define a constructor which can pass this string to the superclass constructor.

Program to demonstrate User Defined Exceptions 

package com.hubberspot.exception.example;

class InvalidMonthException extends Exception
{
  public String toString()
  {
    return "Invalid Month given";
  }
}
class InvalidDayException extends Exception
{
  public String toString()
  {
    return "Invalid Date given";
  }
}
class UserExceptionDemo
{
  public static void main(String[] args)
  {
    try
    {
     if(args.length < 3)
       throw new NullPointerException();
     else
     {
       int dd = Integer.parseInt(args[0]);
       int mm = Integer.parseInt(args[1]);
       int yy = Integer.parseInt(args[2]);
       if(dd < 1 || dd > 31)
          throw new InvalidDayException();
       if(mm < 1 || mm > 12)
                throw new InvalidMonthException();
                  System.out.println("Valid Input");
     }
   }
   catch(Exception e)
        {
System.out.println(e);
}
 }
}

Output 1: java UserExceptionDemo 
 java.lang.NullPointerException

Output 2: java UserExceptionDemo 24 6 2011
 Valid Input

Output 3: java UserExceptionDemo 24 16 2012
 Invalid Month given

Output 4: java UserExceptionDemo 31 2 2012
 Invalid Date is given





Video tutorial to demonstrate how to create user-defined or application specific exceptions in Java.











 
© 2021 Learn Java by Examples Template by Hubberspot