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

2020-05-29 12:54发布

问题:

For example:

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

In other words, is it legal to put the try-block right after the if condition?

回答1:

The syntax of a try block (which is a statement in C++) is

try compound-statement handler-sequence

And the syntax of if is:

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

where:

statement-true - any statement (often a compound statement), which is executed if condition evaluates to true
statement-false - any statement (often a compound statement), which is executed if condition evaluates to false

So yes, your code is legal code in C++.

statement_true in your case is a try block.

In legality, it is similar to:

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

But your code is not very readable and can be the victim of some C++ pitfalls when an else is added. So, it is advisable to add explicit {...} after if in your case.



回答2:

is it legal to put the try-block right after the if condition?

It is legal. Your code is same as (and better to write as):

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

So if the condition is false then the try-catch block won't be executed. If this is what you expect, it's fine.



回答3:

Yes. The braces of an if are optional. Imagine you have {} around the try { .. } catch { .. }.

It may interest you to know that this is what happens when you write if/else if/else; C++ doesn't actually have else if … so this:

if (A) {

}
else if (B) {

}

is actually parsed as this:

if (A) {

}
else
   if (B) {

   }

which is this:

if (A) {

}
else {
   if (B) {

   }
}


回答4:

It's well-formed. try-blocks are statements as per [stmt.stmt]/1, and statements are following if (…) as per [stmt.select]/1.