Wednesday 25 July 2012

stdexcept exception Library

<stdexcept>, <exception>

The standard library provides a hierarchy of exception types. Not all of them are used by the library, but any may be thrown.
Type Header Thrown by
exception stdexcept, exception
logic_error stdexcept
length_error stdexcept
domain_error stdexcept
out_of_range stdexcept .at(i) (vector/string/deque index out of bounds)
invalid_argument stdexcept, bitset bitset("xxx") (not '0' or '1')
runtime_error stdexcept
range_error stdexcept
overflow_error stdexcept
underflow_error stdexcept
bad_alloc new new, new[] (out of memory)
bad_cast typeinfo dynamic_cast<T&> (can't convert to derived)
bad_typeid typeinfo typeid(*p) when p==0
bad_exception exception
ios_base::failure ios, iostream, fstream istream::clear(), ostream::clear()
Catching a base class catches all derived classes, thus catch(exception e) catches all of the above types. However, C++ allows throwing exceptions not derived from exception, so this may not catch everything. All exceptions provide the following interface: throw exception(msg) // Throw exception with char* or string msg
throw exception(); // Default msg
catch(exception e) {e.what();} // msg as a char*

New exceptions may be derived from existing types to maintain this interface (see inheritance).
class MyError: public exception {
public:
MyError(const string& msg=""): exception(msg) {}

No comments:

Post a Comment