class User{
private int age;
void getAge(int age) throws Exception{ //throw关键字的作用是哪个类调用该函数,则哪个类需进行异常声明
if (age<0){
Exception e=new Exception("年龄不能小于零");
throw e;
}
this.age=age;
}
}
class Test{
public static void main(String args[]){
try{
User user=new User();
user.getAge(-12);
}
catch(Exception e){
System.out.println(e);
}
}
}
若使用运行时异常,则代码如下:
class User{
private int age;
void getAge(int age){
if (age<0){
RuntimeException e=new RuntimeException("年龄不能小于零");
throw e;
}
this.age=age;
}
}
class Test{
public static void main(String args[]){
User user=new User();
user.getAge(-9);
}
}