Creating custom exceptions
Create a class and inherit that class with Exception class and
override getMessage() and toString() methods.
Example:
class NoDataFoundException extends Exception
{
public String getMessage()
{
return "Sorry! No Data Provided";
}
public String toString()
{
return "NoDataFoundException : Sorry! No Data Provided";
}
}
public class Number
{
private int num;
public Number()
{
num=-1;
}
public Number(int num) throws Exception
{
if(num<1) throw new Exception("Sorry! Number must be greater
than 0");
this.num=num;
}
public long factorial() throws Exception
{
if(num==-1)
throw new NoDataFoundException();
long f=1;
for(int i=1;i<=num;i++)
f=f*i;
return f;
}
}
class Test
{
public static void main(String args[])
{
try
{
Number x=new Number();
System.out.println(x.factorial());
}catch(Exception ex)
{
System.out.println(ex.toString());
}
}
}



