linternetsansfil
linternetsansfil

Reputation: 199

How to handle errors with std::vector?

std::vector allocates memory which can fail, but the constructor can't return anything, should we use try and catch every time we declare an std::vector ?

I know this question might have already been answered but I didn't find anything, please comment links.

Upvotes: 3

Views: 1539

Answers (1)

rustyx
rustyx

Reputation: 85452

Yes, the default allocator used in std::vector can throw in critical conditions like "out-of-memory". Unhandled exceptions automatically call std::terminate(), which by itself is a good enough handler for these situations, since they should normally never occur (on modern systems with virtual memory, std::bad_alloc is rarely a sign of insufficient memory, and instead a sign of an error in the program, like trying to allocate a negative amount).

So "do nothing" is a good enough way to handle a potentially throwing std::vector.

On Linux you'd get terminate called after throwing an instance of 'std::bad_alloc', what(): std::bad_alloc, Aborted (core dumped).

Unfortunately there are platforms (e.g. Windows) where std::terminate() prints nothing.

For best portability you can thus catch all std exceptions globally to print some meaningful error message just before exiting. For example:

int main() {
    try {

        // program code ...

    } catch (std::exception const& e) {
        std::cerr << "Exception: " << e.what() << std::endl;
        exit(1);
    }
}

Also don't forget to treat any additional threads, if any, in a similar way.

In any case, an individual try-catch per std::vector instance would be overkill.

Upvotes: 3

Related Questions