Search code examples
c#code-contracts

Can a [pure] function throw an exception?


Is it OK for a function that can throw an exception to have the [pure] attribute?


Solution

  • According to

    https://msdn.microsoft.com/en-us/library/system.diagnostics.contracts.pureattribute(v=vs.110).aspx

    PureAttribute attribute

    Indicates that a type or method is pure, that is, it does not make any visible state changes.

    So it's quite possible to throw an exception from such a method e.g.

    // factorial is a pure function: no state will be changed, 
    // just a computation 
    [Pure]
    public static BigInteger Factorial(BigInteger value) {
      // We can't return infinity with BigInteger and that's why have to throw the exception 
      if (value < 0)
        throw new ArgumentOutOfRangeException("value", "value must be non-negative"); 
    
      ...
    }
    

    And what if I call this pure method as

      BigInteger result = Factorial(1000000000);
    

    one of the possible outcomes is OutOfMemory exception thrown