开发者

Error control in constructors

开发者 https://www.devze.com 2023-03-23 18:16 出处:网络
There is such class: class C开发者_开发问答ircle{ int x; int y; int radius; public: Circle(int x_, int y_, int radius_){

There is such class:

class C开发者_开发问答ircle{
  int x;
  int y;
  int radius;
public:
  Circle(int x_, int y_, int radius_){
    x = x_;
    y = y_;
    if(radius < 0)
      signal error;
    radius = radius_;
  }
};

It is not possible to create circle with radius less than zero. What is a good method to signal error in constructor? I know that there are exceptions, but are there any other methods?


A good method is not to allow the error to compile!

Unfortunately, merely using unsigned will not prevent a negative value from being passed to the constructor – it will just be converted implicitly to an unsigned value, thus hiding the error (as Alf pointed out in a comment).

The “proper” solution would be to write a custom nonnegative (or more generally, constrained_value) type to make the compiler catch this error – but for some projects this may be too much overhead, since it can easily lead to a proliferation of types. Since it improves (compile-time) type safety, I still think that this is fundamentally the right approach.

A simple implementation of such a constrained type would look as follows:

struct nonnegative {
    nonnegative() = default;
    template <typename T,
              typename = typename std::enable_if<std::is_unsigned<T>::value>::type>
    nonnegative(T value) : value{value} {}

    operator unsigned () const { return value; }

private:
    unsigned value;
};

See it in action

This prevents construction from anything but an unsigned type. In other words, it simply disables the usual implicit, lossy conversion from signed to unsigned numbers.

If the error cannot be caught at compile time (because the value is received from the user), something like exceptions are the next best solution in most cases (although an alternative is to use an option type or something similar).

Often you would encapsulate this throwing of an exception in some kind of ASSERT macro. In any case, user input validation should not happen inside a class’ constructor but immediately after the value has been read from the outside world. In C++, the most common strategy is to rely on formatted input:

unsigned value;
if (! (std::cin >> value))
    // handle user input error, e.g. throw an exception.


No. Throw an exception — that is the standard way to bail out from the ctor.


Throw an exception. That's what RAII is all about.


Exception is the correct way to signal the error. Because, passing a negative value as a radius is a logical mistake. It's safe to throw from constructor.

As other option, you can print an error message into a log file.

Third option is somewhat suggested by @Luchian; I am rephrasing it.

Don't call the constructor, if the radius it < 0. You should have a check outside the object creation.

Edit: there is a logical error in your code:

if(radius < 0)  // should be 'radius_'


Exception is the best method to report an error from constructor in C++. It is much safe and clear than all others methods. If an error occures in constructor, the object should not be created. Throwing exception is the way to achieve this.


My personal opinion is that you should use throw std::runtime_error in the general case, and as UncleBens points out in comments, invalid_argument in this case.

In some circumstances, like when it is guaranteed that the radius can't be negative by means of unpredictable input, you should use assert instead, because then it is a programmer error (== bug):

#include <cassert>

...
    assert (radius >= 0);

This disables the check for release builds.

A third alternative would be to use your own datatype that guarantees as a post-condition that it's never less than 0; though one has to be careful not to invent too many micro-types:

template <typename Scalar, bool ThrowRuntimeError>
class Radius {
public:
    Radius (Scalar const &radius) : radius_(radius) {
        assert (radius>=Scalar(0));
        if (ThrowRuntimeError) {
            if (Scalar(0) >= radius) throw std::runtime_error("can't be negative");
        }
    }

    ...

private:
    Radius(); // = delete;

    Scalar radius_;
};

Note that in such general implementations, one must be careful to avoid compiler warnings that warn about unneeded comparisons against zero (e.g. when Scalar = unsigned int).

Anyways, I'd go without the Radius class, and use assertations (if negative radius can only be a bug) or exceptions (if negative radius can be the result of bad input).


The standard approach for error in constructors is using an exception.

However an alternative that is sometime useful is the "zombie" approach. In other words if you cannot construct a working object properly then create an object that is non-functional but that can be tested for this and that can be destroyed safely. All the methods should also fail gracefully and become NOPs.

Most of the times this approach is just an annoyance because you will delay the discovery of a problem to when the object is actually used... but it is a viable path if you have serious reasons for avoiding exceptions.


Strictly to C++ - no... Exceptions are the only one 'good' way...

However there are many other 'less-standard' approaches, I recommend two-phase constructors(used in symbian).


Just another possibility to add to what's already here: you could mimic what people do in ML-ish languages and make a "smart constructor":

Circle* makeCircle(...) { ... }

that may return NULL.

Though I agree throwing an exception is probably want you want here.


Consider setting the radius in a init() method which you call after the constructor.

0

精彩评论

暂无评论...
验证码 换一张
取 消