Skip to content

Implement Try-methods without try-catch #504

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:

publicstaticboolTryConvertByName(FromValueinputValue,stringquantityName,stringfromUnit,stringtoUnit,outdoubleresult)
{
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);
returntrue;
}
catch
{
result=0;
returnfalse;
}
}

publicstaticboolTryConvertByAbbreviation(FromValuefromValue,stringquantityName,stringfromUnitAbbrev,stringtoUnitAbbrev,outdoubleresult,
stringculture)
{
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);
returntrue;
}
catch
{
result=0;
returnfalse;
}
}

(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>
publicstaticboolTryParse([CanBeNull]stringstr,[CanBeNull]IFormatProviderprovider,outTemperatureDeltaresult)
{
provider=provider??UnitSystem.DefaultCulture;
try
{
result=Parse(str,provider);
returntrue;
}
catch
{
result=default(TemperatureDelta);
returnfalse;
}
}

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions