Contract exceptions should be handled differently from ordinary exceptions, because a contract should specify a fact about your program that should be true 100% of the time, regardless of the state of the system. If a contract fails, it means that you almost certainly have a bug in your code. The Code Contracts team have provided another way of discovering failures which might be useful in this case (see section 7, "Runtime Contract Behavior" in the manual).
You have two options: you can either provide an event handler for the ContractFailedEvent (which is what I'd recommend in this case), or alternatively provide a complete replacement for the Contract Runtime class (see the manual for more details of this one).
The event handler should be registered as early as possible:
static void Main(string[] args)
{
InitialiseContractHandler();
//...
}
public static void InitialiseContractHandler()
{
Contract.ContractFailed += (sender, eventArgs) =>
{
eventArgs.SetHandled();
eventArgs.SetUnwind();
MyContractFailureLogger(eventArgs);
Assert.Fail(eventArgs.Message);
};
}
The reason I'd use this pattern is so that you can also call the initialising method from an AssemblyInitializer method for unit testing purposes.
Setting the failure as handled this way will prevent the contract runtime from throwing exceptions itself, which is why I've included the Assert.Fail() - after all, you will still want execution to terminate.