Write User Defined Exception in Java

/* Write a program User Defined Exception in Java */
It required to define java custom Exceptions also called User-defined Exceptions.
This can be done by extending the class Exception.
import java.io.*;
class AgeException extends Exception
{
AgeException(String msg)
{
super(msg);
}
}

class TestException
{
public static void main(String args[])
{
String name,s;
BufferedReader br;
int age=15;
try
{
br=new BufferedReader(new InputStreamReader(System.in));
System.out.println(“\n enter Name “);
name=br.readLine();
System.out.println(“\n enter Age “);
s=br.readLine();
age=Integer.parseInt(s);

if(age<0 || age>100)
{
throw new AgeException(“age is invalid “);
}
System.out.println(“\nName: “+name+”\nage:”+age);
}
catch(AgeException e)
{
System.out.println(e.getMessage());
}
catch(IOException e)
{
System.out.println(“Error”);
}
}
}

Leave a Reply