pros and cons of TryCatch versus TryParse

此生再无相见时 提交于 2020-01-13 08:08:56

问题


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

回答1:


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



回答2:


TryParse is more efficient than TryCatch performance wise.




回答3:


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.




回答4:


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


来源:https://stackoverflow.com/questions/2431836/pros-and-cons-of-trycatch-versus-tryparse

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