| - demand explanation
| - realization of ideas
1, create a subclass of Exception, for throwing an exception
2, to create a class used to collect user data collection and age determination
3, create a test class, which is written try - catch statement
| - Content Code
. 1 public class NumException the extends Exception { 2 // create a subclass of Exception, NumException for the job type of an abnormality . 3 public NumException (String Message) { . 4 Super (Message); . 5 System.err.println ( "data entry errors " ); 6 } 7 }
1 public class AgeJuge { 2 private int age; 3 4 public int getAge() { 5 return age; 6 } 7 8 public void setAge(int age) throws NumException { 9 if (age > 100 || age < 0) { 10 throw new NumException("年龄必须在0-100之间"); 11 } else { 12 this.age = age; 13 } 14 } 15 }
1 public class AgeTest { 2 public static void main(String[] args) { 3 Scanner sc = new Scanner(System.in); 4 AgeJuge age = new AgeJuge(); 5 System.out.println("请输入年龄"); 6 try { 7 age.setAge(sc.nextInt()); 8 } catch (NumException e) { 9 e.printStackTrace(); 10 } 11 } 12 }
| --- operating results