Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception swallowed when doing drag and drop

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());

  }

}
like image 374
Julien Poulin Avatar asked Jun 09 '09 13:06

Julien Poulin


1 Answers

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.

like image 97
Viper Avatar answered Sep 21 '22 09:09

Viper