Customized Exceptions (User-defined Exceptions)
• Sometimes we can create our own exception to meet our programming requirements.Such types of exceptions are called customized exceptions (user-defined exceptions).
Example:
1) InSufficientFundsException
2) TooYoungException
3) TooOldException
Program:
class TooYoungException extends RuntimeException
{
TooYoungException(String s)
{
super(s);
}
}
class TooOldException extends RuntimeException
{
TooOldException(String s)
{
super(s);
}
}
class CustomizedExceptionDemo
{
public static void main(String[] args){
int age=Integer.parseInt(args[0]);
if(age>60)
{
throw new TooYoungException("please wait some more time.... u will get best match");
}
else if(age<18)
{
throw new TooOldException("u r age already crossed....no chance of getting married");
}
else
{
System.out.println("you will get match details soon by e-mail");
}
}
}
Output:
1) E:\scjp>java CustomizedExceptionDemo 61
Exception in thread "main" TooYoungException:
please wait some more time.... u will get best match
at CustomizedExceptionDemo.main(CustomizedExceptionDemo.java:21)
2) E:\scjp>java CustomizedExceptionDemo 27
You will get match details soon by e-mail
3) E:\scjp>java CustomizedExceptionDemo 9
Exception in thread "main" TooOldException: u r age already crossed....no chance of getting
married
at CustomizedExceptionDemo.main(CustomizedExceptionDemo.java:25)
Note: It is highly recommended to maintain our customized exceptions as unchecked by
extending RuntimeException.
• We can catch any Throwable type including Errors also.
Example:
Comments
Post a Comment