Sunday, November 25, 2018

java User defined Exception subclass

User defined Exception subclass

You can also create your own exception sub class simply by extending java Exception class. You can define a constructor for your Exception sub class (not compulsory) and you can override the toString() function to display your customized message on catch.
class MyException extends Exception
  {
   private int ex;
   MyException(int a)
   {
    ex=a;
   }
   public String toString()
   {
    return "MyException[" + ex +"] is less than zero";
   }
  }

  class Test
  {
   static void sum(int a,int b) throws MyException
   {
    if(a<0)
    {
     throw new MyException(a); //calling constructor of user-defined exception class
    }
    else
    {
     System.out.println(a+b);
    }
   }

   public static void main(String[] args)
   {
    try
    {
     sum(-10, 10);
    }
    catch(MyException me)
    {
     System.out.println(me); //it calls the toString() method of user-defined Exception
    }
   }
 }
MyException[-10] is less than zero

Points to Remember

  1. Extend the Exception class to create your own exception class.
  2. You don't have to implement anything inside it, no methods are required.
  3. You can have a Constructor if you want.
  4. You can override the toString() function, to display customized message.
Share:

0 comments:

Post a Comment

Contact Form

Name

Email *

Message *

Popular Posts

Blog Archive

Blog Archive

Hassan.mosmer1@gmail.com