实现代码:
/**
* @author Administrator
* 用户信息
*/
public class User {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
//setAge设置输入年龄,并判断是否符合条件,不符合就使用throw抛出异常
public void setAge(int age) throws Exception {
if(age > 0 && age <= 100) {
this.age = age;
}else {
//抛出异常信息
throw new Exception("年龄必须在1到100之间!");
}
}
}
import java.util.Scanner;
public class UsreDome {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
User user = new User();
System.out.println("请输入姓名:");
user.setName(input.next());
System.out.println("请输入年龄:");
//捕获setAge抛出的异常信息并处理
try {
user.setAge(input.nextInt());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
运行结果: