I have a general question regarding the syntax of throwing an object. Consider:
#include <stdio.h>
struct bad { };
void func() {
throw bad;
}
int main(int, char**) {
try {
func();
} catch(bad) {
printf("Caught\n");
}
return 0;
}
This code does not compile (g++ 4.4.3), as the ‘throw’ line must be replaced with:
throw bad();
Why is this? If I’m creating a stack-allocated bad, I construct it like so:
bad b;
// I can't use 'bad b();' as it is mistaken for a function prototype
I’ve consulted Stroustrup’s book (and this website), but was unable to find any explanation for what seems to be an inconsistency to me.
doesn’t work because
badis a data type, a structure (struct bad). You cannot throw a data type, you need to throw an object, which is an instance of a data type.You need to do:
because that creates an object
objofbadstructure and then throws that object.