Write a program to implement the concept of Exception Handling by creating user-defined exceptions.

Program Code:
import java.lang.Exception;
import java.lang.*;
import java.lang.Exception;
import java.io.DataInputStream;
class MyException extends Exception
{
MyException(String message)
{
super(message);
}
}
class userdef
{
public static void main(String a[])
{
int age;
DataInputStream ds=new DataInputStream(System.in);
try
{
System.out.println("Enter the age (above 15 and below 25) :");
age=Integer.parseInt(ds.readLine());
if(age<15 || age> 25)
{
throw new MyException("Number not in range");
}
System.out.println(" the number is :" +age);
}
catch(MyException e)
{
System.out.println("Caught MyException");
System.out.println(e.getMessage());
}
catch(Exception e){ System.out.println(e); }
}
}


Output 1:
Enter the age (above 15 and below 25) :
20
the number is :20

Output 2:
Enter the age (above 15 and below 25) :
6
Caught MyException
Number not in range
Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment:

0 comments: