In: Computer Science
An exceptions lab.
Program:
import java.util.*;
//custom exception for blank name
class BlankException extends Exception
{
BlankException(String str)
{
super(str);
}
}
//custom exception for invalid age
class InvalidException extends Exception
{
InvalidException(String str)
{
super(str);
}
}
class EnterInfo
{
public static void main(String args[])
{
String name,age;
Scanner sc=new Scanner(System.in);
while(true)
{
try
{
System.out.print("Enter your name: ");
name=sc.nextLine();
if(name.equals(""))
{
throw new BlankException("Name should not be blank!!");
}
System.out.print("Enter your age(0 > age > 120): ");
age=sc.next();
Integer.parseInt(age);
if(Integer.parseInt(age)<0 ||
Integer.parseInt(age)>120)
{
throw new InvalidException("Age has to be greater than 0 and less
than 120");
}
break;
}
catch(BlankException be)
{
System.out.println(be);
}
catch(InvalidException ie)
{
System.out.println(ie);
sc.nextLine();
}
catch(NumberFormatException nf)
{
System.out.println(nf);
sc.nextLine();
}
}
}
}
Output: