Is (condition) an attempt {...} legal in C ++?

For example:

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

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

+44
c ++ language-lawyer exception try-catch
Mar 14 '16 at 10:54 on
source share
4 answers

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

 try compound-statement handler-sequence 

And the if syntax 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) that is executed if the condition evaluates to true
statement-false - any (often a compound statement) that is executed if the condition evaluates to false

So your code is legal code in C++ .

statement_true in your case is a try block.

In law, it looks like:

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

But your code is not very readable and may fall prey to some C ++ pitfalls when adding else . Thus, it is advisable to add an explicit {...} after if in your case.

+77
Mar 14 '16 at 10:57
source share

Is it possible to put a try block immediately after the if condition?

This is legal, your code is the same as (and better written 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 will not be executed. If this is what you expect, that’s fine.

+40
Mar 14 '16 at 10:55
source share

Yes. if braces are optional. Imagine that you have {} around try { .. } catch { .. } .

You may be interested to know what happens when you write if / else if / else ; In C ++ there is virtually no else if & hellip; so that:

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

actually analyzed as follows:

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

which is:

 if (A) { } else { if (B) { } } 
+21
Mar 14 '16 at 11:12
source share

He is well formed. try-blocks are statements according to [stmt.stmt] / 1 , and statements follow if (…) according to [stmt.select] / 1 .

+9
Mar 14 '16 at 10:59
source share



All Articles