Throw keyword in function's signature
What is the technical reason why it is considered bad practice to use the C++ throw
keyword in a function signature?
bool some_func() throw(myExc)
{
...
if (problem_occurred)
{
throw myExc("problem occurred");
}
...
}
Solution 1:
No, it is not considered good practice. On the contrary, it is generally considered a bad idea.
http://www.gotw.ca/publications/mill22.htm goes into a lot more detail about why, but the problem is partly that the compiler is unable to enforce this, so it has to be checked at runtime, which is usually undesirable. And it is not well supported in any case. (MSVC ignores exception specifications, except throw(), which it interprets as a guarantee that no exception will be thrown.
Solution 2:
Jalf already linked to it, but the GOTW puts it quite nicely why exception specifications are not as useful as one might hope:
int Gunc() throw(); // will throw nothing (?)
int Hunc() throw(A,B); // can only throw A or B (?)
Are the comments correct? Not quite.
Gunc()
may indeed throw something, andHunc()
may well throw something other than A or B! The compiler just guarantees to beat them senseless if they do… oh, and to beat your program senseless too, most of the time.
That's just what it comes down to, you probably just will end up with a call to terminate()
and your program dying a quick but painful death.
The GOTWs conclusion is:
So here’s what seems to be the best advice we as a community have learned as of today:
- Moral #1: Never write an exception specification.
- Moral #2: Except possibly an empty one, but if I were you I’d avoid even that.
Solution 3:
To add a bit more value to all the other answer's to this question, one should invest a few minutes in the question: What is the output of the following code?
#include <iostream>
void throw_exception() throw(const char *)
{
throw 10;
}
void my_unexpected(){
std::cout << "well - this was unexpected" << std::endl;
}
int main(int argc, char **argv){
std::set_unexpected(my_unexpected);
try{
throw_exception();
}catch(int x){
std::cout << "catch int: " << x << std::endl;
}catch(...){
std::cout << "catch ..." << std::endl;
}
}
Answer: As noted here, the program calls std::terminate()
and thus none of the exception handlers will get called.
Details: First my_unexpected()
function is called, but since it doesn't re-throw a matching exception type for the throw_exception()
function prototype, in the end, std::terminate()
is called. So the full output looks like this:
user@user:~/tmp$ g++ -o except.test except.test.cpp
user@user:~/tmp$ ./except.test
well - this was unexpected
terminate called after throwing an instance of 'int'
Aborted (core dumped)