Re: Throwing unexpected exceptions
On Jun 16, 10:50 am, Urs Thuermann <u...@isnogud.escape.de> wrote:
In Stroustrup's "The C++ programming language" I read that throwing an
exception that is not declared to be expected in a function causes
std::unexpected() to be called. I tried the difference with the follow=
ing code
#include <iostream>
#ifdef NO_EXCPT
int foo() throw()
#else
int foo() throw(int)
#endif
{
throw 1;
}
int main()
{
try {
foo();
} catch (...) {
std::cerr << "Exception c=
aught\n";
}
}
But my question is, is there any good reason to intentionally throw
unexpected exceptions?
How would you, the programmer, know what exceptions
your function might throw? How do you define 'throw'?
Consider the function
void f()
{
std::vector<double> v;
v.reserve(1e80); // Not enough memory
}
Clearly, few systems have enough memory available to
accomodate the requested amount of memory, so the
call v.reserve() will throw a bad_alloc exception.
But which class / function 'threw'? Your function?
std::vector<T>::reserve() ?
If not, shouldn't the compiler warn about code
that clearly does so, i.e. the above code with NO_EXCPT defined?
How would the compiler be able to analyze all the
internal code to deduce which exceptions might and
which might not be thrown? One might easily imagine
a situation where your function calls a pre-compiled
library, that might throw. How would the compiler
be able to analyze that kind of situation?
Not at all obvious.
Rune