![]()
1 package com.Ex01;
2 /**
3 * 使用throw抛出年龄异常
4 *
5 * @author L
6 *
7 */
8 public class Age {
9 private int age;//年龄
10
11 public int getAge() {
12 return age;
13 }
14 //setAge对年龄进行判断,如果年龄介于1到100直接赋值,否则抛出异常
15 public void setAge(int age) throws Exception {
16 if(age>0&&age<=100) {
17 this.age = age;
18 }else {
19 //抛出异常
20 throw new Exception("年龄必须在1到100之间!");
21 }
22 }
23
24 }
1 package com.Ex01;
2
3 import java.util.Scanner;
4
5 public class Test {
6 static Scanner sc=new Scanner(System.in);
7 public static void main(String[] args) {
8 Age age=new Age();
9 System.out.print("请输入年龄:");
10 try {
11 age.setAge(sc.nextInt());
12 }catch(Exception e) {
13 e.printStackTrace();
14 }
15 }
16 }
![]()