pros and cons of TryCatch versus TryParse

前提是你 提交于 2019-12-05 02:18:41
  • 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;
}

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);
   }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!