none
Is "try ... otherwise" provides equal performance in comparison with checking the circumstanses leading to an error? RRS feed

  • Question

  • In other words, what code is quicker:

    one = 1
    zero = 0
    try one/zero otherwise "not use 0 here"
    
    OR
    
    if zero = 0 then "not use 0 here" else one/zero

    Of course this is a simplified example.



    Saturday, March 23, 2019 11:44 PM

Answers

  • Hi Andrey. Generally it should be faster to check simple conditions ahead of time rather than waiting for an error to occur (which usually involves a .NET framework exception being thrown and caught). But the difference between the two may not be noticeable.

    Ehren

    Tuesday, March 26, 2019 8:03 PM
    Owner

All replies

  • Hi Andrey,

    I have not been able determine any discernable difference in performance between using try...otherwise and if ...else when an error occurs.

    However, the example you've given is a common mistake that many people make (several examples in this forum). In M, division by 0 does not generate an error. It returns positive or negative infinity, depending on the sign of the numerator. Therefore, in this case, the expression in the otherwise clause will never be executed. The if...else expression must be used if you don't want to return infinity.

    Monday, March 25, 2019 4:17 PM
  • Hi Andrey. Generally it should be faster to check simple conditions ahead of time rather than waiting for an error to occur (which usually involves a .NET framework exception being thrown and caught). But the difference between the two may not be noticeable.

    Ehren

    Tuesday, March 26, 2019 8:03 PM
    Owner
  • Hi Ehren,

    In the case of try with error, a lazily evaluated error record is created. Are the error details in the record (assuming an error has been thrown) based on a .NET framework exception?

    Tuesday, March 26, 2019 9:58 PM
  • Because the M runtime is implemented in C#, all M errors are .NET exceptions behind the scenes. AFAIK, they all inherit from a custom exception type we define (ValueException), which inherits indirectly from System.Exception. A ValueException can be thrown for a variety of reasons. In some cases, we throw a ValueException based on a condition encountered during evaluation. In other cases, an exception might be thrown by the code of the .NET Framework that we depend on; we then catch this exception, and in turn throw a ValueException that has its own message, reason, etc.

    Ehren

    Tuesday, March 26, 2019 10:20 PM
    Owner
  • Hi Ehren,

    Thanks for the excellent explanation!

    Wednesday, March 27, 2019 1:20 PM