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);
}
}