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?
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?
It is legal. Your code is same as (and better to write as):
So if the condition is
false
then thetry-catch
block won't be executed. If this is what you expect, it's fine.It's well-formed. try-blocks are statements as per [stmt.stmt]/1, and statements are following
if (…)
as per [stmt.select]/1.The syntax of a
try
block (which is a statement in C++) isAnd the syntax of
if
is:where:
So yes, your code is legal code in
C++
.statement_true
in your case is atry
block.In legality, it is similar to:
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{...}
afterif
in your case.Yes. The braces of an
if
are optional. Imagine you have{}
around thetry { .. } catch { .. }
.It may interest you to know that this is what happens when you write
if
/else if
/else
; C++ doesn't actually haveelse if
… so this:is actually parsed as this:
which is this: