4

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

Jan Mattsson
  • 154
  • 2
  • 9

3 Answers3

4

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

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
2

You can throw an exception, you are not making any visible state changes. Here example from Reference source.

    [Pure]
    private void VerifyWritable() {
        if (isReadOnly) {
            throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
        }
        Contract.EndContractBlock();
    }
mybirthname
  • 17,949
  • 3
  • 31
  • 55
-2

I agree with Dmitry.

According to documentation from msdn:

All methods that are called within a contract must be pure; that is, they must not update any preexisting state. A pure method is allowed to modify objects that have been created after entry into the pure method.

Throwing an exception is allowed and will not necessarily be considered as a changing the object state.

Diemauerdk
  • 5,238
  • 9
  • 40
  • 56