一、Throw和throws区别:
1、书写:throws定义在方法名上,throw定义在方法体内
2、作用:throws声明异常,throw抛出异常
3、语法:throws 异常类 throw 异常对象
4、Throws 异常类1,.....,异常n throw 异常对象
二、用throw抛出异常,代码如下:
package ThrowDemo;
public class Person {
private int age;private String sex;
public void Setsex(String sex)throws Exception{
if(sex!="男" && sex!="女"){
throw new Exception("性别必须为“男”或“女”!");
}else{
this.sex=sex;
}
}
public void Setage(int age)throws Exception{
if(age>=1 && age<=100){
this.age=age;
}else{
throw new Exception("年龄必须在1到100之间!");
}
}
package ThrowDemo;
public class ThrowException {
public static void main(String[] args) {
Person per=new Person();
try{
per.Setsex("男");
per.Setage(111);
}catch(Exception e){
e.printStackTrace();
}
}
}