Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find out which exceptions std::map methods can throw?

Tags:

c++

map

I would like to handle exceptional circumstances when using std::map (C++) methods, as well as when using things like boost::unordered_map methods. However, looking at method documentation (e.g.: insert) doesn't provide a list of exceptions that I can catch.

like image 517
Jorge Peach Avatar asked Jun 26 '13 06:06

Jorge Peach


2 Answers

Look at good documentation: if you're not sure then - ultimately - the Standard, but e.g. http://en.cppreference.com/w/cpp/container/map/insert may be more convenient and has an Exceptions heading covering most variants (hopefully will be completed someday). You're not likely to find better documentation for boost than that kept online at the boost site.

If a good reference doesn't document exceptions, it's usually because that function's code isn't explicitly written to throw any - though that doesn't mean there can't be exceptions thrown as the arguments to a function are prepared, as a side effect of memory allocation or some reasonable operation on objects e.g. copy construction or operators, or during the construction of a result. All that's common sense though.

The Standard's explicit requirements re std::map...

23.2.4.1 Exception safety guarantees [associative.reqmts.except]

1 For associative containers, no clear() function throws an exception. erase(k) does not throw an exception unless that exception is thrown by the container’s Compare object (if any).

2 For associative containers, if an exception is thrown by any operation from within an insert() function inserting a single element, the insert() function has no effect.

3 For associative containers, no swap function throws an exception unless that exception is thrown by the swap of the container’s Compare object (if any).


23.4.4.3 map element access [map.access]

T& at(const key_type& x);

const T& at(const key_type& x) const;

10 Throws: An exception object of type out_of_range if no such element is present.

like image 74
Tony Delroy Avatar answered Nov 10 '22 11:11

Tony Delroy


Jorge,

Standard containers can only throw an out-of-range exception on access, they do not throw exceptions on other operations. However, the contained items can throw in an inner operation (constructor, assignation, comparison) when this operation is overloaded. That's why @tony-d link gives the best answer : this documents the behavior of the container when some underlying element raise during manipulations (insert/clear/swap).

The only exception left that can be raised are memory access violations and out-of-memory errors, which you should handle globally (and very carefully) at every high level, if at all.

like image 41
lip Avatar answered Nov 10 '22 10:11

lip