首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >让构造函数抛出异常是一种好的做法吗?

让构造函数抛出异常是一种好的做法吗?
EN

Stack Overflow用户
提问于 2011-05-22 14:00:58
回答 4查看 175.8K关注 0票数 194

让构造函数抛出异常是一种好的做法吗?例如,我有一个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;
  }
}
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6086334

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档