package com.uek.test;
public class TestThrowAndThrows {
//throw 和throws的区别
/*
* 1.位置不同throw位于方法体中,throws位于方法声明中
* 2.内容不同throw后面跟一个异常对象,throws后面跟一个或多个异常类
* 3.作用不同 throw:此处有异常,我负责抛出,这里是抛出的源头,
* throws该方法中有异常但是没有try—catch,我负责声明,告诉调用者
*/
private String name ="";//姓名
private int age = 0; //年龄
private String sex = "男"; //性别
public void setSet(String sex) throws Exception{
if("男".equals(sex)||"女".equals(sex)) {
this.sex=sex;
}
else {
throw new Exception("请输入正确 的性别男和女");
}
}
public static void main(String[] args) {
TestThrowAndThrows ts = new TestThrowAndThrows();
try {
//调用的方法有异常,所以要解决异常,才能进行接下来程序的运行
ts.setSet("aa");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//上面进行try catch解决了异常,程序就会继续执行
//这里输出的是默认值
System.out.println(ts.sex);
}
}
2021-09-18throw和throws异常的区别
最新推荐文章于 2022-10-31 17:11:58 发布