定义Person类,包含name与age两个成员变量。
在Person类的有参数构造方法中,进行年龄范围的判断,
若年龄为负数或大于200岁,则抛出《0》异常,
异常提示信息“年龄数值非法”。
自定义异常类。使用自定义异常类。
public class NoAgeException extends Exception {
public NoAgeException(String message) {
super(message);
}
}
public class Person {
private String name;
private int age;
public Person(String name, int age) throws NoAgeException {
this.name = name;
if(age<0 || age>=200){
throw new NoAgeException("年龄数值非法");
}
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
import java.util.*;
public class test {
public static void main(String[] args) throws NoAgeException {
Scanner x = new Scanner(System.in);
System.out.println("请输入学生姓名");
String sname = x.next();
System.out.println("请输入学生年龄");
int sage = x.nextInt();
Person ad = new Person(sname,sage);
System.out.println(ad.getName()+" "+ad.getAge());
}
}
import java.util.*;
public class test {
public static void main(String[] args) {
Scanner x = new Scanner(System.in);
System.out.println("请输入学生姓名");
String sname = x.next();
System.out.println("请输入学生年龄");
int sage = x.nextInt();
try{
Person ad = new Person(sname,sage);
System.out.println(ad.getName()+" "+ad.getAge());
}catch (Exception e){
System.out.println(e.getMessage());
System.out.println(e.toString());
System.out.println(e);
}finally {
System.out.println("程序运行结束");
}
}
}