相关疑难解决方法(0)

使构造函数抛出异常是一种好习惯吗?

使构造函数抛出异常是一个好习惯吗?例如,我有一个类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)

java constructor exception

155
推荐指数
8
解决办法
13万
查看次数

标签 统计

constructor ×1

exception ×1

java ×1