您的位置:首页 > 职场人生

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

2014-01-12 10:43 323 查看
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();
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: