In ASP.NET I can use Application_Error
within global.开发者_StackOverflow中文版asax in order to handle any errors that have been unhandled.
Is there an equivalent in windows forms?
Yes its AppDomain.UnhandledException
using System;
using System.Security.Permissions;
public class Test {
[SecurityPermission(SecurityAction.Demand, Flags=SecurityPermissionFlag.ControlAppDomain)]
public static void Example()
{
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);
try {
throw new Exception("1");
} catch (Exception e) {
Console.WriteLine("Catch clause caught : " + e.Message);
}
throw new Exception("2");
// Output:
// Catch clause caught : 1
// MyHandler caught : 2
}
static void MyHandler(object sender, UnhandledExceptionEventArgs args) {
Exception e = (Exception) args.ExceptionObject;
Console.WriteLine("MyHandler caught : " + e.Message);
}
public static void Main() {
Example();
}
}
[STAThread]
static void Main()
{
Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
Application.Run(new FrmMain());
}
private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
MessageBox.Show("Unhandled exception: "+e.Exception.ToString());
}
It depend on the architecture of your app. For exemple, if you do MVC architecture then it should be in your controler.if you know Chain of responsability pattern[GOF] or if you prefer a big handler of all type of execption. Otherwise, you'll to tell us more about your app.
精彩评论