Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle incorrect values in a constructor?

Tags:

Please note that this is asking a question about constructors, not about classes which handle time.

Suppose I have a class like this:

class Time { protected:     unsigned int m_hour;     unsigned int m_minute;     unsigned int m_second; public:     Time(unsigned int hour, unsigned int minute, unsigned int second); }; 

While I would want a to be constructed successfully, I would want the constructor of b to fail.

Time a = Time(12,34,56); Time b = Time(12,34,65); // second is larger than 60 

However, this is not possible, because constructors do not return any values and will always succeed.

How would the constructor tell the program that it is not happy? I have thought of a few methods:

  1. have the constructor throw an exception, and have handlers in the calling function to handle it.
  2. have a flag in the class and set it to true only if the values are acceptable by the constructor, and have the program check the flag immediately after construction.
  3. have a separate (probably static) function to call to check the input parameters immediately before calling the constructor.
  4. redesign the class so that it can be constructed from any input parameters.

Which of these methods is most common in industry? Or is there anything I may have missed?

like image 947
Andy Avatar asked Jul 21 '09 10:07

Andy


People also ask

How do you handle a constructor error?

The best way to signal constructor failure is therefore to throw an exception. If you don't have the option of using exceptions, the "least bad" work-around is to put the object into a "zombie" state by setting an internal status bit so the object acts sort of like it's dead even though it is technically still alive.

Can constructor return error?

It's not possible to use error code since constructors don't have return types.

What happens if constructor fails?

If an exception is thrown in a constructor, the object was never fully constructed. This means that its destructor will never be called. Furthermore, there is no way to access an object in an error state. The exception will immediately unwind the local variable.

Can we throw exception from constructor in C++?

When throwing an exception in a constructor, the memory for the object itself has already been allocated by the time the constructor is called. So, the compiler will automatically deallocate the memory occupied by the object after the exception is thrown.


1 Answers

The typical solution is to throw an exception.

The logic behind that is the following: the constructor is a method that transforms a chunk of memory into a valid object. Either it succeeds (finishes normally) and you have a valid object or you need some non-ignorable indicator of a problem. Exceptions are the only way to make the problem non-ignorable in C++.

like image 75
sharptooth Avatar answered Jan 04 '23 04:01

sharptooth