创建一个测试类,测试异常的抛出,异常的抛出处理案例

package seday07.exception;
/**
* @author xingsir
* 测试异常的抛出,测试类
*/

public class Person {
private int age;//创建个年龄属性

/*
* 右键点-Source-点 -generate getters and setters,选择要生成的属性
*/
public int getAge() {
return age;
}

public void setAge(int age) throws Exception {//使用throw new时 此处需需要throws添加异常捕获
if(age<0||age>=130) {//判断年龄在0到130之间为真
throw new Exception("不在范围内");//添加异常捕获
}

this.age = age;
}

}

//====================================================================================

package seday07.exception;

/**
* @author xingsir
* 异常的抛出处理案例
*/
public class ThrowDemo {

public static void main(String[] args) {
Person p = new Person();

/*
* 我们调用含有throws声明异常抛出的方法时,编译器要求我们必须处理该异常,
* 处理异常的方式有两种:
* 1:使用try-catch捕获并处理抛出的异常类型
* 2:在当前方法上继续使用throws声明异常的抛出
* 具体使用哪种,结合实际业务需求而定。
*/
try {
p.setAge(1000);//调用此方法为Person类的一个方法,调用时判断
} catch (Exception e) {
e.printStackTrace();//输出错误堆栈信息,有助于定位并解决错误
}
System.out.println(p.getAge());//此时的返回值为0

}

}