The standard does not forbid its usage within [basic.start.main], and, while forcing all implementations to support at least int main() {/*...*/ }
and int 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:
Exceptions thrown in destructors of objects with static storage
duration or in constructors of namespace-scope objects are not caught
by a function-try-block on main(). (15.3 para. 13)
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 that main()
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:
Flowing off the end of a function-try-block is equivalent to a return
with no value; this results in undefined behavior in a value-returning
function (6.6.3). (15.3 para. 15)
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 calls return 0;
on flowover doesn't apply. You need to return some int
(quite possibly an error code) to keep from becoming undefined.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…