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

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)