如果(条件)尝试 {..} 在C++合法

Is if (condition) try {...} legal in C++?

本文关键字:C++ 合法 尝试 条件 如果      更新时间:2023-10-16

例如:

if (true) try
{
    // works as expected with both true and false, but is it legal?
}
catch (...)
{
    // ...
}

换句话说,将 try-block 放在 if 条件之后是否合法?

try块(这是C++中的语句)的语法为

try compound-statement handler-sequence

if的语法是:

attr(optional) if ( condition ) statement_true      
attr(optional) if ( condition ) statement_true else statement_false     

哪里:

statement-true - 任何语句(通常是复合语句),其中 如果条件计算结果为 true statement-false则执行
- 任何 语句(通常是复合语句),在 if 条件下执行 计算结果为 false

所以是的,您的代码是 C++ 中的合法代码.

在您的情况下statement_true是一个try块。

在合法性上,它类似于:

if (condition) for(...) {
    ...
}

但是您的代码不是很好读,并且在添加else时可能会成为一些C++陷阱的受害者。因此,建议您在if后添加显式{...}

将 try-block 放在 if 条件之后是否合法?

这是合法的。您的代码与以下内容相同(最好编写为):

if (true) {
    try
    {
        // works as expected with both true and false, but is it legal?
    }
    catch (...)
    {
        // ...
    }
}

因此,如果条件false则不会执行try-catch块。如果这是您所期望的,那很好。

是的。if的大括号是可选的。想象一下,您在try { .. } catch { .. }周围{}

您可能会感兴趣,当您写if/else if/else时,就会发生这种情况;C++实际上没有else if... 所以这个:

if (A) {
}
else if (B) {
}

实际上解析为:

if (A) {
}
else
   if (B) {
   }

这是:

if (A) {
}
else {
   if (B) {
   }
}

它的格式很好。try-blocks 是符合 [stmt.stmt]/1 的语句 s,语句 s 是按照 [stmt.select]/1 遵循的语句if (…)