Search code examples
.neterror-handlingcode-contracts

How to handle code contract violations on run-time


I visited devday11 in the Netherlands last week and learned about Code Contract. I am thinking about implementing Code Contract, but the following is still unclear to me. How should I handle runtime code contract violations in my application?

For example I have a layer in my application that calls another layer with a null value. The function called had a Required Contact, so it throws a contract validation error. How should this be handled? So something like this

public string GetOrderSomething(OrderModel order)
{
 Contract.Requires(order != null);
 // jibidi jibeda do something
 }  

//other application layer
private void something()
{
 Class.GetOrderSomething(null);
}

What should be done? Should I handle it with a normal try catch, should I not handle it at all? Is there something "special" I should do?


Solution

  • Assuming you already have an 'exception handling' policy in place, you should not have to do anything special.

    If would be advisable to pick a specific exception:

    public string GetOrderSomething(OrderModel order)
    {
      Contract.Requires<ArgumentNullException> (order != null, "order");
      // jibidi jibeda do something
    }
    

    Now you can handle the ArgumentNullException in the same manner and place(s) as you would without (before) using contracts.

    PS: Hope you liked the talk.