【发布时间】:2019-05-26 12:15:49
【问题描述】:
我想在我的应用程序中捕获所有未处理的异常。所以我用这段代码来捕获所有未处理的异常:
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
SaveEx(e.Exception);
Application.Exit();
}
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
SaveEx((Exception)e.ExceptionObject);
Application.Exit();
}
static void SaveEx(Exception ex)
{
bool exists = System.IO.Directory.Exists(Path.GetDirectoryName(@"C:\AppLogs\"));
if (!exists)
System.IO.Directory.CreateDirectory(Path.GetDirectoryName(@"C:\AppLogs\"));
String filePath = @"C:\AppLogs\" + DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss") + ".txt";
String log = "===========Start=============\r\n";
log += "Error Message: " + ex.Message + "\r\n";
log += "Stack Trace: " + ex.StackTrace + "\r\n";
log += "===========End=============";
System.IO.File.WriteAllText(filePath, log);
}
}
我试图用 0 分来引发这些异常:
在主线程上完美运行:
int t = 0;
int r = 5 / t;
但是当我尝试在 Thread 中执行此操作时:
Thread thread = new Thread(delegate()
{
int t = 0;
int r = 5 / t;
});
thread.Start();
CurrentDomain_UnhandledException 函数被调用,但它一直在我的代码中调用int r = 5 / t; 行,所以我有一个异常循环。知道可能是什么问题吗?线程只被调用一次。
【问题讨论】:
-
你怎么称呼
thread.Start(),我的意思是在哪里? -
Application.Exit() 不是终止应用程序的正确方法,它只会让车轮运转。当汽车撞到墙上时,你已经没有轮子了。请改用 Environment.Exit()。
-
@AliBahrami 我在按钮点击事件中使用它
-
@HansPassant 不是因为这个,我已经删除了,还是有这个问题。
-
当您可以向我们展示时,推测“我已经删除它”可能意味着什么并不是很有用。指导是替换它。
标签: c# multithreading winforms exception