Create new exception class

Java allows programmer to create their own exception. why we need to create exception? Take a example in java there is no data type to store date. So we create new class Date. Now we know that date can be from 1 to 31 and month can be from 1 to 12. What if date or month assigned is out of specified range. for that we want to create our own exception.


To create any exception class, our class has to inherit Exception class. To print details of exception toString() method need to be specified.

Example


class DateException extends Exception
{
int date;
int month;
DateException(int d,int m)
{
date=d;
month=m;
}
public String toString()
{
String s="Error in date["+date+"] or mothd ["+month+"]";
s=s+"\nDate format Exception";
return s;
}
}


Above class is defined as new exception. toString method is used to print details of exception.



class Date
{
int date;
int month;
int year;
Date()
{
date=1;
month=1;
year=1900;
}
Date(int d,int m, int y) throws DateException // This constructor can throw DateException
{
if(0<date<32)
date=d;
else
throw new DateException(d,m);
if(0<month<13)
month=m;
else
throw new DateException(d,m);
year=y;
}

}
class use
{
public static void main(String arg[]) throws DateException // main method having code that can generate DateException
{
Date d1=new Date(1,2,2003);
Date d2=new Date(0,2,2002);
}
}
/*Output:
Exception in thread "main" Error in date[1] or month [2]
Date format Exception
at Date.(use.java:34)
at use.main(use.java:47)
*/