Why do try..catch blocks require braces?

前端 未结 3 1597
深忆病人
深忆病人 2021-02-11 13:32

While in other statements like if ... else you can avoid braces if there is only one instruction in a block, you cannot do that with try ... catch blocks: the compiler doesn\'t

3条回答
  •  情话喂你
    2021-02-11 13:52

    Straight from the C++ spec:

    try-block:
        try compound-statement handler-seq
    

    As you can see, all try-blocks expect a compound-statement. By definition a compound statement is multiple statements wrapped in braces.

    Have everything in a compound-statement ensures that a new scope is generated for the try-block. It also makes everything slightly easier to read in my opinion.

    You can check it yourself on page 359 of the C++ Language Specification

提交回复
热议问题