Friday, May 3, 2019

user defined exception

Example 1:


class clexc extends Exception
{
public clexc(String s)
{

super(s);
}
}

public class clex
{

public static void main(String args[])
{
try
{

throw new clexc("my exception");
}
catch (clexc ex)
{
System.out.println("exception Caught");

System.out.println(ex.getMessage());
}
}
}


output::

D:\>javac clex.java

D:\>java clex
exception Caught
my exception

D:\>




Example 2:

class clexc extends Exception
{    private int v;
public clexc(String s)
{

super(s);
}
     public clexc(int a){v=a;}
     public String toString(){ return "exc"+v+"pp";}


}

public class clex
{
static void compute(int a) throws clexc
        { System.out.println("compute function"+a);
          if(a>10)
             throw new clexc(a);
          System.out.println("no throw");
           
        }
public static void main(String args[])
{
try
{

compute(1);
}
catch (clexc ex)
{
System.out.println("exception Caught");

System.out.println(ex.getMessage());
}
}
}



D:\>javac clex.java

D:\>java clex
compute function1
no throw

D:\>


Example 3:

class clexc extends Exception
{    private int v;
public clexc(String s)
{

super(s);
}
     public clexc(int a){v=a;}
     public String toString(){ return "exc"+v+"pp";}


}

public class clex
{
static void compute(int a) throws clexc
        { System.out.println("compute function"+a);
          if(a>10)
             throw new clexc(a);
          System.out.println("no throw");
           
        }
public static void main(String args[])
{
try
{

compute(11);
}
catch (clexc ex)
{
System.out.println("exception Caught");

System.out.println(ex.getMessage());
}
}
}

output:


D:\>javac clex.java

D:\>java clex
compute function11
exception Caught
null

D:\>



No comments:

Post a Comment