Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "Contract can't be in try block" mean?

I'm using the 3.5 library for microsoft code contracts

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 the compiler message: "Error 18 Contract section within try block in method 'Controller.RetrieveById(System.Int32)'

UPDATE:

I figured it out with your help:

  • Move to top
  • Check against Contract.Result

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

like image 811
MatthewMartin Avatar asked May 21 '10 15:05

MatthewMartin


2 Answers

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

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

it says:

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

So just leave the Ensures call at the top of the method and you should not get any problems.

like image 53
Jason Evans Avatar answered Sep 18 '22 02:09

Jason Evans


It's pretty simple: the Contract class signals contract violations by throwing an exception. Putting it in a try block defeats the purpose, you're liable to catch the exception.

like image 28
Hans Passant Avatar answered Sep 21 '22 02:09

Hans Passant