Skip to content

Implement Try-methods without try-catch #504

@angularsen

Description

@angularsen

Try methods should generally be implemented to avoid exceptions, if possible, to be more performant.
This means, use Try methods internally and pessimistically check for conditions that may fail.
Any exceptions that leak out should be the result of unrecoverable errors, such as OutOfMemoryException and similar.

Some examples, but search for all of them:

public static bool TryConvertByName(FromValue inputValue, string quantityName, string fromUnit, string toUnit, out double result)
{
try
{
// TODO Reimplement to avoid exceptions where possible, as Try methods are generally recommended for performance and this is cheating
// https://msdn.microsoft.com/en-us/library/ms229009(v=vs.100).aspx
result = ConvertByName(inputValue, quantityName, fromUnit, toUnit);
return true;
}
catch
{
result = 0;
return false;
}
}

public static bool TryConvertByAbbreviation(FromValue fromValue, string quantityName, string fromUnitAbbrev, string toUnitAbbrev, out double result,
string culture)
{
try
{
// TODO Reimplement to avoid exceptions where possible, as Try methods are generally recommended for performance and this is cheating
// https://msdn.microsoft.com/en-us/library/ms229009(v=vs.100).aspx
result = ConvertByAbbreviation(fromValue, quantityName, fromUnitAbbrev, toUnitAbbrev, culture);
return true;
}
catch
{
result = 0;
return false;
}
}

(generated for N quantities)

/// <summary>
/// Try to parse a string with one or two quantities of the format "&lt;quantity&gt; &lt;unit&gt;".
/// </summary>
/// <param name="str">String to parse. Typically in the form: {number} {unit}</param>
/// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="UnitSystem.DefaultCulture" />.</param>
/// <param name="result">Resulting unit quantity if successful.</param>
/// <example>
/// Length.Parse("5.5 m", new CultureInfo("en-US"));
/// </example>
public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out TemperatureDelta result)
{
provider = provider ?? UnitSystem.DefaultCulture;
try
{
result = Parse(str, provider);
return true;
}
catch
{
result = default(TemperatureDelta);
return false;
}
}

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions