Search code examples
c#.nettryparsetry-catch

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

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