Inside Try/Catch, Visual Studio breaks and ends app on Unhandled exception

后端 未结 1 1191
清酒与你
清酒与你 2020-12-21 10:54

I\'m getting different behavior when running the same code inside and outside the Visual Studio.

Private Sub MyAppli         


        
相关标签:
1条回答
  • 2020-12-21 11:26

    This question has many moving parts, not sure I can do justice to all of them. Starting point is that you should not subscribe those events if you use a debugger. Wrap that code with If Not System.Diagnostics.Debugger.IsAttached Then so you can properly diagnose and repair unhandled exceptions.

    A significant randomizer is what will happen with exceptions that are thrown in a Load event handler. Microsoft had a great deal of trouble properly handling exceptions that are raised while a Windows callback is active. Such as the one that causes the Load event to fire. They changed the rules at Vista, again at Win7, again at Win8. They are different if you run the 32-bit of the 64-bit version. And whether your program runs as a 32-bit or 64-bit process. Using a debugger alters the behavior. The Program Compatibility Assistant may appear when the exception occurs, asking you if you want your program to be "compatible". Everybody says Yes of course, a very bad idea. Adding them up, you can get one of thirty-two different outcomes. Ouch.

    It is formally described in this MSDN article but nobody understands it. Not until it doesn't do what they hope for, covered in a question like this one. Mitigating circumstance is that this only bytes when you debug an app, the normal exception back-stop in the message loop ensures this doesn't get out of hand on your user's machine. In other words, what you see when you press Ctrl+F5 or run the program with Explorer is the way you can expect it to work.

    This is a problem that affects any GUI program on Windows. But it has a knack of being especially troublesome in a Winforms app, programmers use the Load event entirely too much. Deluded into it by it being the default event for the Form class, it takes but a double-click to generate it. Especially so in VB.NET, it doesn't automatically create the constructor for a form and Visual Basic has a legacy of using the Load event to initialize a form, goes back to VB6.

    I normally avoid judging programming practices I see, but using the Load event is today a really rather bad practice because of these problems. Always favor the constructor to initialize a class, a rule that any .NET programmer knows, it isn't different for the Form class. There are exceedingly few reasons to have to use Load, covered in this post.

    0 讨论(0)
提交回复
热议问题