自定义两个 Java 异常,抛出性别与年龄异常。
请按以下步骤要求编写代码:
AgeException 异常类:
public class RegisterException extends Exception {
public RegisterException() {
}
public RegisterException(String message) {
super(message);
}
}
SexException 异常类:
public class Test {
// 需求:用户名已经存在异常
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入用户名:");
String username = sc.nextLine();
try {
register(username);
} catch (RegisterException e) {
e.printStackTrace();
}
}
public static void register(String username)throws RegisterException{
// 假设 haicoder 已经被注册
if("haicoder".equals(username)){
throw new RegisterException("用户名已注册,请重新输入!");
}else{
System.out.println("恭喜您,"+ username +" 注册成功");
}
}
}
Student 类:
public class Student {
private String name;
private String sex;
private int age;
public Student() {
}
public Student(String name, String sex, int age) {
this.name = name;
this.sex = sex;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex){
if(!sex.equals("男") && !sex.equals("女")){
throw new SexException("性别异常!!");
}
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
if(age < 15 || age > 50){
throw new AgeException("年龄异常!!");
}
this.age = age;
}
}
测试类:
public class Test {
public static void main(String[] args) {
System.out.println("嗨客网(www.haicoder.net)\n");
Student stu = new Student();
stu.setName("haicoder");
// 性别异常
try{
stu.setSex("无");
}catch(SexException e){
System.out.println(e.getMessage());
}
// 年龄异常
try{
stu.setAge(100);
}catch (AgeException e){
System.out.println(e.getMessage());
}
}
}
运行结果如下图:
以上案例实现自定义异常处理学生类年龄和性别异常。