Search code examples
c++assertc++20

Should I use exceptions for checking valid input?


I am using gcc10.2, c++20.

I am studying c++ after 2 years of python.

In python we always did run-time check for input validity

def createRectangle(x, y, width, height): # just for example
    for v in [x, y, width, height]:
        if v < 0:
            raise ValueError("Cant be negative")
    # blahblahblah

How would I do such process in c++?


Solution

  • for (int v : {x, y, width, height})
        if (v < 0)
            throw std::runtime_error("Can't be negative");
    

    Note that such loop copies each variable twice. If your variables are heavy to copy (e.g. containers), use pointers instead:

    for (const int *v : {&x, &y, &width, &height})
        if (*v < 0)
            ...
    

    Comments also suggest using a reference, e.g. for (const int &v : {x, y, width, height}), but that will still give you one copy per variable. So if a type is that heavy, I'd prefer pointers.