使构造函数抛出异常是一个好习惯吗?例如,我有一个类Person,我有age它的唯一属性.现在我提供课程为
class Person{
int age;
Person(int age) throws Exception{
if (age<0)
throw new Exception("invalid age");
this.age = age;
}
public void setAge(int age) throws Exception{
if (age<0)
throw new Exception("invalid age");
this.age = age;
}
}
Run Code Online (Sandbox Code Playgroud)