package cn.yichang; public class NameAge { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) throws Exception{//抛出异常 if(age >100||age <0) { throw new Exception("年龄必须在1到100之间!"); //System.out.println("你的年龄不在范围内"); }else { this.age = age; } } }
package cn.yichang; import java.util.Scanner; public class Main { static Scanner sc = new Scanner(System.in); public static void main(String[] args) { NameAge na = new NameAge (); System.out.print("请输入你的姓名:"); String name = sc.next(); try { System.out.print("请输入年龄:"); int age = sc.nextInt(); na.setAge(age); }catch(Exception e) { e.printStackTrace(); } } }