Vijesh
Vijesh

Reputation: 261

pros and cons of TryCatch versus TryParse

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;
    }
}

Upvotes: 15

Views: 6672

Answers (5)

zille_elahi
zille_elahi

Reputation: 79

In some cases it is better to proactively look or check for the input against using try catch block. Example if we have a dictionary with lookup table for ineteger to string conversion it is good performance wise if we just use ContainsKey instead of using try catch for checking the key

Upvotes: 0

onof
onof

Reputation: 17367

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);
   }
}

Upvotes: 2

John Knoeller
John Knoeller

Reputation: 34128

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.

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1499860

  • 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;
}

Upvotes: 23

Sunil
Sunil

Reputation: 1979

TryParse is more efficient than TryCatch performance wise.

Upvotes: 4

Related Questions