I did a custom made exception but I am not sure if it is correct and also I don't know why is a case of an exception the program is not printing the message for the exception but only the name of the class for the custom exception, and also how can I make it in a case of an exception to terminate the program because in the moment the program only informs about the exceptions and go on. The program is compiling and running on eclipse. Cheers guys. Here is the code.
import java.util.Scanner;
public class Stud
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter age of the student");
int age = input.nextInt();
try
{
if(age < 7 || age > 18)
{
throw new InvalidStudentException("Age can't be less than 7 and more than 18");
}
}
catch(InvalidStudentException e)
{
System.err.println(e) ;
}
System.out.println("Enter the gender of the student");
String gender = input.next();
try
{
if((!gender.equals("male")) || (!gender.equals("female")))
{
throw new InvalidStudentException("Gender can be only male or female");
}
}catch(InvalidStudentException e)
{
System.err.println(e) ;
}
System.out.println("Enter the name of the student");
String name = input.next();
try
{
if(name.length() < 10 || name.length() > 50)
{
throw new InvalidStudentException("The length of the name must be greater than 10 and less than 50 characters");
}
}catch(InvalidStudentException e)
{
System.err.println(e) ;
}
System.out.println("Enter the class number for the student");
int classNumber = input.nextInt();
try
{
if(classNumber < 1 || classNumber > 11)
{
throw new InvalidStudentException("Class number can be only between 1 and 11");
}
}catch(InvalidStudentException e)
{
System.err.println(e) ;
}
}
}
/** the class with the custom made exception
*/
public class InvalidStudentException extends Exception
{
String msg;
int num;
public InvalidStudentException()
{
super();
}
public InvalidStudentException(String msg)
{
super();
this.msg = msg;
}
public InvalidStudentException(int num)
{
super();
this.num = num;
}
}