Saturday, March 29, 2014

User Defined Exception Example in Java

/*
Write a class Student with attributes roll no, name, age and course. Initialize values through parameterized constructor. If age of student is not in between 15 and 21 then generate user-defined exception “Age Not Within The Range”.If name contains numbers or special symbols raise exception “Name not valid
*/

import java.io.*;
class AgeNotWithinRangeException extends Exception
{
AgeNotWithinRangeException()
{
super();
}
}

class NameNotValidException extends Exception
{
NameNotValidException()
{
super();
}
}
class Student
{
private
int roll,age;
String name,course;

public
Student(int r,String nm,int ag,String co)
{
roll=r;
name=nm;
age=ag;
course=co;

System.out.println("Roll Number is "+roll);
System.out.println("Name is "+name);;
System.out.println("Age is "+age);
System.out.println("Course is "+course);
}

public static void main(String args[]) throws IOException
{

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int roll,age;
String name,course;
System.out.println("Enter No. :");
roll = Integer.parseInt(br.readLine());
System.out.println("Enter Name :");
name = br.readLine();
try
{
for(int i=0;i<name.length();i++)
{
char c = name.charAt(i);

if((c<65 || c>90) && (c<97 || c>122) && (c!=32))
{
throw new NameNotValidException();
}//if
}//for
}//try
catch(NameNotValidException n)
{
System.out.println("Invalid Name"+n);
}
System.out.println("Enter Age :");
age = Integer.parseInt(br.readLine());
try
{
if(age<15 || age>21)
{
throw new AgeNotWithinRangeException();
}
}//try

catch(AgeNotWithinRangeException e)
{
System.out.println("Invalid Age"+e);
}

System.out.println("Enter Course :");
course = br.readLine();

Student s = new Student(roll,name,age,course);
}
}

2 comments:

  1. Given so much info in it, These type of articles keeps the users interest in the website, and keep on sharing more .
    java training in chennai

    ReplyDelete