import java.util.Scanner;
public class zidingy7 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String name;
int age;
System.out.print("请输入名字:");
name = input.next();
System.out.print("请输入年龄:");
age = input.nextInt();
Person person = null;
try {
person = new Person(name, age);
} catch (NoAgeException e) {
e.printStackTrace();
}
System.out.println(person.name + ":" + person.age);
}
}
//创建异常类
class NoAgeException extends Exception {
public NoAgeException() {
}
public NoAgeException(String message) {
super(message);
}
}
//创建Person类
class Person {
String name;
int age;
public Person() throws NoAgeException {
}
public Person(String name, int age) throws NoAgeException {
if (age > 50 || age < 18) {
throw new NoAgeException("年龄非法年龄不能小于18岁也不能大于50岁");
} else {
this.name = name;
this.age = age;
}
}
}
运行结果