黑马程序员——throw和throws的区别

来源:互联网 发布:数据录入员有前途吗 编辑:程序博客网 时间:2024/05/18 03:32


1.作用不同:throw用于程序员自行产生并抛出异常,throws用于声明在该方法内抛出了异常。
2.使用的位置不同:throw位于方法体内部,可以作为单独语句使用。throws必须跟在方法参数列表的后面,不能单独使用。
3.内容不同:throw抛出一个异常对象,而且只能是一个。throws后面跟异常类,而且可以跟多个异常类。


例子:
public class Person {
private String name = "";// 姓名
private int age = 0;// 年龄
private String sex = "男";// 性别
public void setSex(String sex) throws Exception {
if ("男".equals(sex) || "女".equals(sex))
this.sex = sex;
else {
//抛出异常
throw new Exception("性别必须是“男”或者“女”!");
}
}
public void print() {
System.out.println(this.name + "(" + this.sex 
+ "," + this.age + "岁)");
}
}






public class Test {
public static void main(String[] args) {
Person person = new Person();
//捕获异常
try {
person.setSex("Male");
person.print();
} catch (Exception e) {
e.printStackTrace();
}
}
}



0 0
原创粉丝点击