Winforms应用程序。这是主要的:
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// Add handler for UI thread exceptions
Application.ThreadException += new ThreadExceptionEventHandler(UIThreadException);
// Force all WinForms errors to go through handler
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
// This handler is for catching non-UI thread exceptions
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
Application.Run(new Form1());
}
private static void CurrentDomain_UnhandledException(Object sender, UnhandledExceptionEventArgs e)
{
Exception ex = (Exception)e.ExceptionObject;
MessageBox.Show("Unhadled domain exception:\n\n" + ex.Message);
Application.Exit();
// It should terminate our main thread so Application.Exit() is unnecessary here
}
private static void UIThreadException(object sender, ThreadExceptionEventArgs t)
{
MessageBox.Show("Unhandled exception catched.\n Application is going to close now.");
// Here we can decide if we want to end our application or do something else
Application.Exit();
}
}
这是我故意产生异常的地方
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
int zero = 0;
//int number = 1 / zero;
throw new System.IO.FileNotFoundException();
}
}
堆栈跟踪:
System.IO.FileNotFoundException was unhandled
HResult=-2147024894
Message=Unable to find the specified file.
Source=NewPostSharpSolution
StackTrace:
at NewPostSharpSolution.Form1..ctor() in C:\Users\Joao\Documents\Visual Studio 2015\Projects\NewPostSharpSolution\NewPostSharpSolution\Form1.cs:line 21
at NewPostSharpSolution.Program.Main() in C:\Users\Joao\Documents\Visual Studio 2015\Projects\NewPostSharpSolution\NewPostSharpSolution\Program.cs:line 30
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
处理程序显示异常的消息框,但仍会中断应用程序...
我有什么想念的吗?我以为实现此处理程序将让我决定如何处理异常?
从MSDN AppDomain.UnhandledException事件:
此事件提供未捕获的异常的通知。它允许应用程序在系统默认处理程序向用户报告异常并终止应用程序之前记录有关异常的信息。
这意味着-您无法处理异常。您可以记录有关异常的信息,显示一些消息等。但是您不能阻止应用程序终止。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句