In C#, WinForms, VS2008, .NET 3.5…
For this code:
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
try
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FormThatDividesByZero());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
public partial class FormThatDividesByZero : Form
{
public FormThatDividesByZero()
{
InitializeComponent();
}
private void DivideByZeroButton_Click(object sender, EventArgs e)
{
// Create a divide by zero exception.
int a = 0;
int b = 0;
int c = a / b;
}
}
Full source: http://forgefx.com/posts/ExceptionReporting.zip
When I run this small test project, via F5, from the development environment, the exception after clicking the DivideByZero button is caught and the message box triggers. When I run the project by double-clicking the .exe in the /bin/Debug folder, the exception is not caught and there is no message box – why is this the case?
When the .exe is launched from outside of the IDE, or with “Debug > Start Without Debugging” from within visual studio, I get an unhandled exception. My understanding was that the code above would catch all exceptions.
This isn’t good way to catch global exception. You can use AppDomain or Application object to catch it. This object catch all unhandled exception and call event.