Reputation: 61
I often write code like this :
try
{
vec.push_back(0);
}
catch(const std::bad_alloc &)
{
ec=1;
}
catch(...)
{
ec=2;
}
Is the ellipsis catch useful? Can you provide some links where I can find everything I need to know about exceptions thrown by cin, vector, ifstream, etc? All C++ things... Something like The Open Group Base Specifications Issue 7 (http://pubs.opengroup.org/onlinepubs/9699919799/) where you can find functions names, parameters, return values, flags, errno codes, etc.
Upvotes: 1
Views: 7055
Reputation: 153955
I haven't seen any restrictions on what exceptions can be thrown but there is footnote 192 which contains this statement:
... Library implementations should report errors by throwing exceptions of or derived from the standard exception classes(18.6.2.1 ,18.8, 19.2).
This a footnote on 17.6.5.12 [res.on.exception.handling] paragraph 4 which also contains this sentence:
... Any other functions defined in the C++ standard library that do not have an exception-specification may throw implementation defined exceptions unless otherwise specified.
It seems, any decent implementation would throw only exceptions derived [indirectly] from std::exception
. That is, I would catch std::exception const&
and probably report the what()
string povided by this exception in some form (e.g., log it to a suitable destination).
Upvotes: 2
Reputation: 1
If an ellipsis catch is really useful is arguable IMHO. You should at least catch a std::exception
for matching the broader case
try {
vec.push_back(0);
}
catch(const std::bad_alloc &) {
ec=1;
}
catch(const std::exception &) {
ec=2;
// You can inspect what() for a particular reason, or even try to dynamic_cast<>
// to find out which specific exception was thrown.
}
catch(...) {
// You have no more type info here, this should be done for last resort (in the
// outermost scope) only.
ec=3;
}
I left comments about the advantages/disadvantages
Upvotes: 3