Wednesday, February 11, 2009

Top-level exception handling

Found a good article on exception handling. Top-level Exception Handling in Windows Forms Applications and followed some advice from it.

What it meant for me, basically, is that I changed the Program.cs file of my application from this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace MyNameSpace
{
static class Program
{
///
/// The main entry point for the application.
///

[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FormUpdater());
}
}
}

to this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Threading;

namespace MyNameSpace
{
static class Program
{
///
/// The main entry point for the application.
///

[STAThread]
static void Main()
{
Application.ThreadException +=
new ThreadExceptionEventHandler(new
ThreadExceptionHandler().ApplicationThreadException);

Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FormUpdater());
}

public class ThreadExceptionHandler
{
public void ApplicationThreadException
(object sender, ThreadExceptionEventArgs e)
{
MessageBox.Show(e.Exception.Message, "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

and that allowed me to get rid of a couple of dozens try/catch blocks in the application code without losing any exception handling functionality. Quite handy.

by . Also posted on my website

No comments: