例子:
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是方法可能抛出异常的声明。(用在声明方法时,表示该方法可能要抛出异常)
语法:[(修饰符)](返回值类型)(方法名)([参数列表])[throws(异常类)]{......}
public void doA(int a) throws Exception1,Exception3{......}