Question

What are the pros and cons of using either of the following approaches to pulling out a double from an object? Beyond just personal preferences, issues I'm looking for feedback on include ease of debugging, performance, maintainability etc.

public static double GetDouble(object input, double defaultVal)
{
    try
    {
        return Convert.ToDouble(input);
     }
     catch
     {
        return defaultVal;
     }
}

public static double GetDouble(object input, double defaultVal)
{
    double returnVal;
    if (double.TryParse(input.ToString(), out returnVal))
    {
        return returnVal;
    }
else
    {
        return defaultVal;
    }
}
Was it helpful?

Solution

  • TryParse will be faster than catching an exception
  • TryParse indicates something expected - nothing exceptional is happening here, it's just that you suspect your data may not be valid.
  • TryParse isn't using exception handling for normal control flow

Basically, go with TryParse :)

By the way, your code can be rewritten as:

public static double GetDouble(object input, double defaultVal)
{
    double parsed;
    return double.TryParse(input.ToString(), out parsed)) ? parsed : defaultVal;
}

OTHER TIPS

TryParse is more efficient than TryCatch performance wise.

Having the Parse methods throw exceptions on bad input was a design flaw. Bad input is expected behavior when you take in data from a user. Exception throwing is expensive, it's not something you want happening routinely in your code.

Thankfully, Microsoft realized their mistake and added the TryParse methods. TryParse does not incur the overhead of exception throwing on bad input, but the downside is it has to return two pieces of data, so it feels a bit awkward to use.

Now if they hadn't created the broken Parse implemetation in the first place, TryParse would just be called Parse.

TryParse is faster and usually better but I would suggest the TryCatch approach in framework and back-end programming because you can give more information to the client about the error:

public double GetAge()
{
   try
   {
      var input = _dataProvider.GetInput();
      return Convert.ToDouble(input);
   }
   catch(Exception ex)
   {
      throw new MyBackendException(ex);
   }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top