Search This Blog

Monday, 3 February 2014

user defined exception in java

/* illustrate the concept of making UserDefinedException in java */


package userdefinedexceptiondemo;

class MyException extends Exception
{
    public String toString()
    {
        return "Exception occured ...";
    }
}

class MyClass 
{
    int a=2,b,c;
    public void Number(int b) throws MyException
    {
        this.b=b;
        if(b<=0)
            throw new MyException();
        else
        {
            c=a/b;
            System.out.println("Answer is : "+c);
        }
    }
}
class MainMethod
{
    public static void main(String[] args)
     {
         try
         {
            MyClass mc=new MyClass();
            // mc.Number(2);  Ouput is : Answer is : 1
            mc.Number(0);
         }
         catch(MyException n)
         {
             System.out.println(n);
         }
         
      }
}

Output

Exception occured ...

No comments:

Popular Posts