我正在和一位同事讨论如何从构造函数中抛出异常,并且我想要一些反馈.
从设计的角度来看,从构造函数中抛出异常是否可以?
假设我在一个类中包装一个POSIX互斥锁,它看起来像这样:
class Mutex {
public:
  Mutex() {
    if (pthread_mutex_init(&mutex_, 0) != 0) {
      throw MutexInitException();
    }
  }
  ~Mutex() {
    pthread_mutex_destroy(&mutex_);
  }
  void lock() {
    if (pthread_mutex_lock(&mutex_) != 0) {
      throw MutexLockException();
    }
  }
  void unlock() {
    if (pthread_mutex_unlock(&mutex_) != 0) {
      throw MutexUnlockException();
    }
  }
private:
  pthread_mutex_t mutex_;
};
我的问题是,这是标准的方法吗?因为如果pthread mutex_init调用失败,则互斥对象不可用,因此抛出异常可确保不会创建互斥锁.
我是否应该为Mutex类创建一个成员函数init,并pthread mutex_init在其中调用将返回基于返回的bool pthread mutex_init?这样我就不必为这种低级对象使用异常.
使构造函数抛出异常是一个好习惯吗?例如,我有一个类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;
  }
}