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);
  }
  else 
  { 
   System.out.println(a+b); 
  }
 }
 public static void main(String[] args)
 {
  try
  {
   sum(-10, 10);
  }
  catch(MyException me)
  {
   System.out.println(me);
  }
 }
}
Points to Remember
- Extend the Exception class to create your own ecxeption class.
- You don't have to implement anything inside it, no methods are required.
- You can have a Constructor if you want.
- You can override the toString() function, to display customized message.
