Create a user defined exception in java

Java Custom Exceptions


Program to create a user defined exception

class Myexception extends Exception
{
            int detail;
            Myexception(int a)
            {
                        detail=a;
            }
            public String toString()
            {
                        return “Myexception[“+detail+”]”;
            }
}
class Userexception
{
            static void compute(int a)throws Myexception
            {
                        System.out.println(“Compute(“+a+”)”);
                        if(a>10)
                        throw new Myexception(a);
                        System.out.println(“Normal Exit”);
            }
            public static void main(String args[])
            {
                        try
                        {
                                    compute(2);
                                    compute(20);
                        }
                        catch(Myexception e)
                        {
                                    System.out.println(e);
                        }
            }
}
 
Output:
Compute(2)
Normal Exit
Compute(20)

Myexception[20]

Leave a Reply

Your email address will not be published. Required fields are marked *

Enable Notifications OK No thanks