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 "<quantity> <unit>". |
|
/// </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; |
|
} |
|
} |
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:
UnitsNet/UnitsNet/UnitConverter.cs
Lines 118 to 132 in 420c2e3
UnitsNet/UnitsNet/UnitConverter.cs
Lines 275 to 290 in 420c2e3
(generated for N quantities)
UnitsNet/UnitsNet/GeneratedCode/Quantities/TemperatureDelta.NetFramework.g.cs
Lines 176 to 199 in 794777d