views:

225

answers:

2

I have a WinForms application where I'm doing drag and drop between 2 TreeViews.

At some point, I want to reject the action in the underlying business implementation, so I throw an Exception. I can see the Exception in the Output window but the problem is that I can't see it in the UI and it doesn't crashes.

Where did the Exception go?

Here is some code that describes the problem:

private TreeView tvLeft;
private TreeView tvRight;
private Dictionary<string, int> dico = new Dictionary<string, int>();

void tvLeft_DragDrop(object sender, DragEventArgs e) {

  if (e.Data.GetDataPresent(typeof(TreeNode))) {

    var tnSource = (TreeNode) e.Data.GetData(typeof(TreeNode));
    var tnDestination = tvLeft.GetNodeAt(tvLeft.PointToClient(new Point(e.X, e.Y)));

    // if I drag-drop the same node twice, there sould be an Exception
    // since the key is already in the dictionary...
    // ...but I get no Exception in the UI, the Application.ThreadException
    // or Appomain.CurrentDomain.UnhandledException handlers
    dico.Add(tnSource.Name, (new Random()).Next());

  }

}
A: 

The exception is probably occurring on a background thread somewhere. you need to create a handler for the AppDomain.CurrentDomain.UnhandledException or the Application.ThreadException event.

See here for some more detail.

Simon P Stevens
I've created both handlers but the Exception doesn't show in any of them. Is there any other?
Julien Poulin
In visual studio, hit Debug->Exceptions, and tick the "thrown" box along side "Common Language Runtime Exception". This should make the debugger break into your code as soon as an exception is thrown and you can use F10/F11 to walk along the path it follows.
Simon P Stevens
+3  A: 

I found this explanation in the internet:

Even with drag-and-drop within the same application, the drag-and-drop is handled through the standard OLE drag-drop mechanism. From OLE's point of view it's dealing with two applications, the source and the target and decouples them appropriately. Since OLE has been around far longer than .NET, OLE has no concept of a .NET exception and therefore can't communicate an exception from the target back to the source. Even if it could, why should the source care that the target couldn't perform the drop? If you want to handle an exception during a DragDrop event you must handle it within your DragDrop event handler, it won't propagate beyond that event handler because there is a managed to unmanaged to managed code transition between the source and the target.

See here the 1st answer after the question.

Viper
Thanks, very interesting post
Julien Poulin