本文介绍了为什么try?catch块需要大括号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

而在其他语句如if ... else你可以避免大括号,如果只有一个块中的一条指令,你不能这样用try ... catch块:编译器不买它。例如:

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 buy it. For instance:

try
    do_something_risky();
catch (...)
    std::cerr << "Blast!" << std::endl;

使用上面的代码,g ++简单地说,它希望在do_something_risky为什么try ... catch之间的行为差​​异,如果... else?

With the code above, g++ simply says it expects a '{' before do_something_risky(). Why this difference of behavior between try ... catch and, say, if ... else ?

谢谢!

推荐答案

直接使用C ++规范:

Straight from the C++ spec:

try-block:
    try compound-statement handler-seq

正如你所看到的,所有 try -block 需要一个复合语句。根据定义,复合语句是用大括号括起来的多个语句。

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

复合语句中的所有内容都确保为try块生成一个新作用域。

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.

您可以在

这篇关于为什么try?catch块需要大括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 15:42