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?
In 'try-catch' the codes to handle the exceptions and what exception to be handled, that are easily readable. In 'if-else', we have one else block corresponding to one if block. Or we need to define another condition with command 'else if'. In 'try-catch' we don't have to define each 'try' block with a 'catch' block.
You should use if / else to handle all cases you expect. You should not use try {} catch {} to handle everything (in most cases) because a useful Exception could be raised and you can learn about the presence of a bug from it.
C has the following conditional statements: Use if to specify a block of code to be executed, if a specified condition is true. Use else to specify a block of code to be executed, if the same condition is false. Use else if to specify a new condition to test, if the first condition is false.
If you've one if/else block instead of one try/catch block, and if an exceptions throws in the try/catch block, then the if/else block is faster (if/else block: around 0.0012 milliseconds, try/catch block: around 0.6664 milliseconds). If no exception is thrown with a try/catch block, then a try/catch block is faster.
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 truestatement-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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With