Interesting question over an internal API design alias:

 

Question: Which is the best way to implement events that developer can cancel.

 

Cancelable events:

In this scenario we would derive the eventArgs from CancelEventArgs so that developers can set the Cancel property if they want to cancel the event.

 

The code would look like:

 

void private FormLoadEventHandler(object sender, FormLoadEventArgs e)

{
  if (user is not authenticated)

  {

    // I don’t want to load the form

    e.Cancel=true;

 }

}

 

 

Throw an exception:

In this case if developers want to cancel the event they will have to throw an exception

 

The code would like:

void private FormLoadEventHandler(object sender, FormLoadEventArgs e)

{
  if(user is not authenticated)

  {

    // I don’t want to load the form

    throw new AbortEventException(“Cannot load”);

 }

}

 

Answer (From Mark Boulter and me):

It sounds like option two is using exceptions as a message passing mechanism which isn’t a good idea pref-wise and does not feel like a natural fit from a user model point of view. You should not throw exceptions to cancel events you should use CancelEventArgs because:

 

  1. Typically the cancellation is an expected result of handling the event and you should not throw exceptions for expected results as mentioned below

 

  1. Throwing exceptions in UI is on the whole a “bad thing” because typically there is no good place for the developer to catch the event – event based UI is non-linear and exceptions rely on linear execution – in many places in Windows Forms we catch exceptions and turn them into error events for precisely this reason