Een heel enkele keer gaat er op een heel diep niveau toch iets mis in je applicatie. Wil op zo'n moment de gebruiker niet opzadelen met zo'n vreselijk CLR Unhandled Exception bericht?
Dat hoeft ook niet. De meeste exceptions kun je afvangen met een try/catch, maar met bijvoorbeeld ThreadException lukt dat niet.
Je kunt een eigen exception handler schrijven om alle unhandled exception toch netjes af te vangen.
Zie hieronder voor een voorbeeld.
//The Error Handler class
//We need a class because event handling methods can't be static
internal class CustomExceptionHandler {
//Handle the exception event
public void OnThreadException(object sender, ThreadExceptionEventArgs t) {
DialogResult result = DialogResult.Cancel;
try {
result = this.ShowThreadExceptionDialog(t.Exception);
}
catch {
try {
MessageBox.Show("Fatal Error",
"Fatal Error",
MessageBoxButtons.AbortRetryIgnore,
MessageBoxIcon.Stop);
}
finally {
Application.Exit();
}
}
if (result == DialogResult.Abort)
Application.Exit();
}
//The simple dialog that is displayed when this class catches and exception
private DialogResult ShowThreadExceptionDialog(Exception e) {
string errorMsg = "An error occurred please contact the adminstrator with" +
" the following information:\n\n";
errorMsg += e.Message + "\n\nStack Trace:\n" + e.StackTrace;
return MessageBox.Show(errorMsg,
"Application Error",
MessageBoxButtons.AbortRetryIgnore,
MessageBoxIcon.Stop);
}
}
....
//Register the custom error handler as soon as we can in Main
//to make sure that we catch as many exceptions as possible
public static void Main(string[] args) {
CustomExceptionHandler eh = new CustomExceptionHandler();
Application.ThreadException += new ThreadExceptionEventHandler(eh.OnThreadException);
Application.Run(new ErrorHandler());
}
Bron: www.gotdotnet.com