自定义跑出异常在类Person中
class Person{
private int age;
public void setAge(int age){
if(age < 0){
RuntimeExcetion e = new RuntionExcetion("年龄不能为负数");
throw e;
}
this.age = age;
}
}
在主函数中若如下调用:
Person p = new Person();
p.setAge(-10);
则抛出相应异常:RunctionExcetion:年龄不能为负数;
在Person类中这样做:
class Person{
private int age;
public void setAge(int age) throw Exxception{
if(age < 0){
Excetion e = new Excetion("年龄不能为负数");
throw e;
}
this.age = age; }}
那么在相应的主函数里要对异常进行抛出:
Person p = new Person();
try{
p.setAge(-10);
}catch(Excetion e){
System.out.println(e);
}
则抛出相应异常:Excetion:年龄不能为负数;