我做了一个自定义异常,但我不确定它是否正确,而且我不知道为什么会出现异常,程序没有打印异常消息,而只打印自定义异常的类的名称,以及如何在出现异常的情况下终止程序,因为此时程序只通知异常并继续。该程序正在eclipse上编译和运行。干杯,伙计们。这是代码。
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;
}
}