Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is if (condition) try {...} 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 legal to put the try-block right after the if condition?

like image 765
Davit Tevanian Avatar asked Mar 14 '16 10:03

Davit Tevanian


People also ask

Can we use if in try?

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.

Should I use if else or try catch?

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.

What is if condition in C?

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.

Is try catch faster than if?

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.


1 Answers

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.

like image 167
Mohit Jain Avatar answered Oct 01 '22 01:10

Mohit Jain