tags:

views:

165

answers:

2

Hi,

Is there a reference about C++ Standard Library Exceptions? I just want to know that which functions may throw an exception or not.

Thank you.

+1  A: 

The only functions guaranteed (by the compiler) to not throw are functions that have the throw() exception specification, like this:

void ThisFunctionNeverThrows() throw()
{
}

Otherwise, any other function can potentially throw an exception, unless they are specifically documented otherwise. You must consider exception safety when writing code in the face of exceptions.

See Bjarne Stroustup's article on exception safety and the standard library: http://www2.research.att.com/~bs/3rd_safe.pdf Starting on page 19 in the PDF you can find information on guarantees made by the standard containers.

In silico
This is not correct as many containers e.g. guarantee not to throw in `erase()`, yet this function is not `throw()`. From language point of view what you wrote does make sense, but there are guarantees other than those specifically enforced by compiler.
doublep
@doublep: `erase()` *will* throw if the copy constructor of the element type throws.
KennyTM
From page 21 in the PDF I mentioned (Guarantees for `vector` and `deque`): "Unless thrown by the copy constructor or the assignment operator of the element type, no `erase()` throws an exception."
In silico
@Kenny: Not all containers copy anything in `erase()`. Of course it can throw in a `vector`, but not in e.g. `list`.
doublep
+5  A: 

Actually, most of the standard library function don't throw exceptions themselves. They just pass on exception thrown by user code invoked by them. For example, if you push_back() an element to a vector, this can throw (due to memory allocation errors and) if the object's copy constructor throws.

A few notable exceptions (no pun intended) where library functions throw are:

  • Some methods will throw out_of_range if the index provided is invalid:
    • std::vector<>::at()
    • std::basic_string<>::at()
    • std::bitset<>::set(), reset() and flip().
  • Some methods will throw overflow_error on integer overflow:
    • std::bitset<>::to_ulong() and (C++0x) to_ullong().
  • std::allocator<T> will pass on out-of-memory exceptions thrown by new which it invokes.
  • Streams can be setup so that exceptions are thrown when a state bit is set.

(I'm making this a CW answer, so if anyone can think of more such, please feel free to append them here.)

Also, for the 3rd edition of The C++ Programming Language, Bjarne Stroustrup has a downloadable appendix about exception safety, which might be relevant.

sbi
+1 for the link. I've just started reading it.
dare2be
Thanks for your answer. By the way, what's the CW answer?
Brian
@Brian: It's "community wiki". Others are free to edit any CW answer (even when they don't have the rep to edit answers normally).
sbi