A little known, but almost never used C++ feature is given a declaration:
void foo();
One possible, legal definition could be:
void foo() try {
throw 42;
}
catch(...) {
}
Here the whole function implementation wrapped is within a try
/catch
pair, which seems to be similar to allowing this.
Is that legal to do for int main()
? E.g.:
int main() try {
throw 42;
}
catch(...) {
}
The rules for main, n3290 § 3.6.1 mostly talk about what arguments it should take and what it returns - they don't seem to explicitly forbid it as they do with various other odd things (e.g. linkages) you might be tempted to try.
Is this legal and well defined?
The standard does not forbid its usage within [basic.start.main], and, while forcing all implementations to support at least
int main() {/*...*/ }
andint main(int argc, char* argv[]) {/*...*/}
, does not limit implementations to those two declarations (3.6.1, para. 2).From that in isolation, it would appear at the least that it is legal, though of course that relates only to function-declarations, not function-definitions.
Reading on, [except.handle], paragraph 13 states the following:
It makes specific mention of a function-try-block placed on
main()
, which strongly implies that such a structure is legal and has defined behavior. Adding in the information thatmain()
is only special in its name and return type, and that implementations may not overload it to alter any behavior, makes a pretty strong case that it acts in a normal fashion except when specially noted such as in the above quote. In other words, yes, it is legal and well-defined.The blog post I supplied in the first version of this answer actually does a good job of illustrating the rules given by the above blockquote, so I'll retain the link to it, even though it does not directly discuss the issue in the OP's question.
Regarding a comment on the OP, you can issue return statements within a function-try-block, and [except.handle] has this to say:
If you're in a catch-block at the end of
main
, you're not going to flow over the function's body (which would be the try-block in this case), so the rule that main automatically callsreturn 0;
on flowover doesn't apply. You need to return someint
(quite possibly an error code) to keep from becoming undefined.I have tried it, it compiles, and it runs as expected. A peculiar formulation, but I don't think it breaks any rules. For clarity (for yourself and future code mantainers), you could also rephrase it as: