vendredi 29 juin 2018

Is it a correct way to use try-catch block over if statement to check a condition?

I was just wondering what's the best practice between using try-catch block to check a condition and an if statement ? For example to try if we are below the range of a List in a loop :

List<int> foo = new List<int>();
for(int cpt=1; cpt<=10; i++)
{
    if (cpt > foo.Count) foo.Add(cpt);
    Console.WriteLine(foo[cpt]);
}

But we can achieve this by using a try-catch like this :

List<int> foo = new List<int>();
int bar = 0;
for(int cpt=1; cpt<=10; i++)
{
    try
    {
        Console.WriteLine(foo[cpt]);
    }
    catch(ArgumentOutOfRangeException)
    {
        foo.Add(cpt);
    }
}

So for this example, obviously the if statement is better as it's able to display the foo[cpt] even if we are out of bound but in another context, could the try-catch block be more efficient ?

Aucun commentaire:

Enregistrer un commentaire