Is there a reference about C++ Standard Library Exceptions? I just want to know that which functions may throw an exception or not.
The C++ Standard library provides a base class specifically designed to declare objects to be thrown as exceptions. It is called std::exception and is defined in the <exception> header.
A C++ exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero. Exceptions provide a way to transfer control from one part of a program to another. C++ exception handling is built upon three keywords: try, catch, and throw.
std::exception::whatReturns a null terminated character sequence that may be used to identify the exception. The particular representation pointed by the returned value is implementation-defined. As a virtual function, derived classes may redefine this function so that specific values are returned.
Strong exception guarantee -- If the function throws an exception, the state of the program is rolled back to the state just before the function call. (for example, std::vector::push_back) Basic exception guarantee -- If the function throws an exception, the program is in a valid state.
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:
out_of_range if the index provided is invalid:
std::vector<>::at()std::basic_string<>::at() std::bitset<>::set(), reset() and flip().std::overflow_error on integer overflow:
std::bitset<>::to_ulong() and (C++0x) to_ullong().std::allocator<T> will pass on std::bad_alloc thrown by new which it invokes. std::ios_base::failure are thrown when a state bit is set. std::bad_array_new_length
std::bad_cast (technically not part of the standard library)std::bad_exception
std::function::operator(...) if it has no value will throw std::bad_function_call.typeinfo of a null pointer may throw a std::bad_typeid.weak_ptr after the pointee has been released will throw a std::bad_weak_ptr.std::promise/std::future may throw a std::future_error.std::stoi, std::stol, std::stoll, std::stoul, std::stoull, std::stof, std::stod, and std::stold can throw both std::invalid_argument and std::out_of_range.std::regex_error.(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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With