黑马程序员——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();
}
}
}
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();
}
}
}
相关文章推荐
- 黑马程序员_throws与throw的区别
- 黑马程序员 throws 与throw有什么区别?
- 黑马程序员——throw于throws的区别
- 黑马程序员—throw和throws的区别
- 黑马程序员—Java基础学习笔记之(throws与throw的区别)
- 黑马程序员———throws与throw区别
- 黑马程序员_throw 和throws区别
- 黑马程序员——throws和throw的区别,try、catch和finally的使用场景
- java面向对象-异常概述-异常声明throws-多异常处理-throw和throws区别
- java异常处理的throw和throws的区别
- throw和throws的区别
- 黑马程序员_java 异常之throws、throw 和 RuntimeException
- throw 和 throws 的区别
- Java中throw和throws的区别
- 【转】关于java异常中的throws和throw的区别
- 【Java基础 001】 throw和throws的区别
- throw 与 throws的区别与联系
- Java异常类简介以及throws,try,catch,throw,finally的区别
- Java中throws和throw的区别讲解
- 异常----RuntimeException与其他的一些区别以及throw与throws的区别