Sometimes it is hard to convince that catch(…) is not so good!

Today I provided code review to one of my colleague and he was totally sure the he need try{/*code*/}catch(){} in few places.

First looked like:

try
{
   int someValueId = Convert.ToInt32(value);
   if (someValueId > 0)
   {
     return new ValidationResult(true, “Valid”);
   }
}
catch{}

I rewrote code to:

int serviceId;
Int32.TryParse(value, out serviceId);
if (serviceId > 0)
{
  return new ValidationResult(true, “Valid”);
}

Then I spent few minutes to convince him that this code is ok and that this is not good to have catch for everything.

Another code looked like:

string result = string.Empty;
try
{
    result = documentContent.Descendants(“SomeValueCode”).FirstOrDefault().Value;
}
catch (Exception)
{
    //He was trying to ensure me that since we are doing validation we should not throw an exception
}
//do some work here

Now I tried to explain that FirstOrDefault() returns us either first element of collection OR null, so if we got null we just need to do some another stuff,
but if some exception will occur we should allow it fly out OR write some specific catch for exceptions that could be thrown. Code which I propose looks like:

var resultElement = documentContent.Descendants(“SomeValueCode”).FirstOrDefault();
if(interventionCodeElement != null)
{
    var result = resultElement.Value;
    //do some work here
}

After conversation we decided that try(/*code*/)catch() is not so good.

If you haven't subsribed yet, you can subsribe below: