In this post you will learn to create your own, user defined exceptions. This program will handle unchecked exceptions, i.e those exceptions which cannot be checked by the compiler, or the run time exceptions. In this program there is a simple class AgeMargin in which when the age is less then 18 or greater then 24 generates an AgeException.
Screenshots[Demo]
The Code:
import java.util.Scanner;
class AgeException extends Exception
{
public String toString()
{
return "AgeException Caught!";
}
}
public class AgeMargin
{
public static void main(String []args)
{
int age;
Scanner s=new Scanner(System.in);
while(true)
{
try
{
System.out.println("Enter The Age: ");
age=s.nextInt();
if(age>=18 && age<=24)
{
System.out.println("The age is within the permitted Range !");
break;
}
else
throw new AgeException();
}
catch(AgeException e)
{
System.out.println(e);
}
}
}
}
Got Suggestions, Bugs ?
Comment them here !



Developer, Tinkere, a proud Dad.. love to spend my available time playing with Tech!!