Mar 072016

ADM

If statement vs try catch block

  • 07 March 2016
  • ADM

 

 

 

If statement vs try catch block - images/logos/java.jpg

 

Real live comparison:

If statement is like walking on the cliff, on each step you need to check your stability otherwise you may fall into abyss.

Try/catch block is like walking on the street, you don't have to care about the road on each step, only when there is an obstacle (something exceptional is happening).

For example if you have a division in a loop result = x /y; the problem that can occurs is when y = 0; (Division by zero).

First option is to use if statement:


//loop
if (y != 0)
{
result = x / y;
}
//end loop

Second option is to use try/catch block:


//loop
try
{
result = x / y;
}
catch (Exception ex)
{
//Log Error
}
//end loop

If you know that y = 0; will be a rare case then you should go with try / catch option otherwise if this will happen often then you should go with if statement option.

...so remember are you walking on a cliff or on a road?