What does “Contract cannot be in try block” mean?

I use library 3.5 for contracts with Microsoft code

public object RetrieveById(int Id) { //stuff happens... Contract.Ensures(newObject != null, "object must not be null"); return newProject; //No error message if I move the Contract.Ensures to here //But it isn't asserting/throwing a contract exception here either } 

I get a compiler message: "Error 18 of the contract section in the try block in the method" Controller.RetrieveById (System.Int32) "

UPDATE:

I figured this out with your help:

  • Go to the top of the page
  • Check out the contract. Result

    Contract.Ensures (Contract.Result ()! = Null, "the object must not be null");

+6
c # code-contracts
source share
3 answers

I might be missing something, but I just looked at the documentation for this:

http://msdn.microsoft.com/en-us/library/dd412865.aspx

He says:

This method call must be at the beginning of the method or property, before any other code.

So just leave the Ensures call at the top of the method and you shouldn't have any problems.

+6
source share

Here's a similar solution:

http://social.msdn.microsoft.com/Forums/en/codecontracts/thread/43f467f1-14b7-4e56-8030-50f842b7ba68

Your recent change shows that you have the code above the Contract.Ensures statement. Contract.Ensures must be present before any other code in your method, therefore:

 public object RetrieveById(int Id) { //first line of method: Contract.Ensures(newObject != null, "object must not be null"); //stuff happens... return newProject; } 
+2
source share

This is pretty simple: the contract class signals a breach of contract by throwing an exception. Putting in a try block hits the target, you can catch an exception.

+2
source share

All Articles