wer*_*rty 5 c# error-handling events exception winforms
在 C# winform 桌面应用程序中,我试图捕获所有可能出现在代码中的异常,我已经尝试过:
using System;
using System.Threading;
using System.Windows.Forms;
namespace Controller
{
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
Application.Run(new Form1());
}
static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
MessageBox.Show(e.Exception.Message, "Unhandled Thread Exception");
}
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
MessageBox.Show((e.ExceptionObject as Exception).Message, "Unhandled UI Exception");
}
}
}
Run Code Online (Sandbox Code Playgroud)
我在设备管理器中使用没有串口的表单关闭事件附加“COM6”来测试它,但我只看到 Visual StudioAn exception of type 'System.InvalidOperationException' occurred in System.dll but was not handled in user code
报告
如何为 winform 应用程序收集错误数据
这其实并不难做到。
我建议将处理异常的任何代码放入主窗体中,以保持program.cs
尽可能干净。
首先在你Program.cs
把这个
static class Program
{
public static Form MainForm = null;
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.ThreadException += Application_ThreadException;
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
MainForm = new Form1();
Application.Run(MainForm);
}
static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
{
((Form1)MainForm).Application_ThreadException(sender, e);
}
}
Run Code Online (Sandbox Code Playgroud)
然后在你的主表单中放这个
public void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
// All unhandled exceptions will end up here, so do what you need here
// log the error
// show the error
// shut the application down if needed
// ROLLBACK database changes
// and so on...
}
Run Code Online (Sandbox Code Playgroud)
Lor*_*nzo -1
在应用程序中的一个点捕获所有错误并不是最佳实践。我建议您确定代码可能在哪里失败,并使用 try/catch 块来捕获特定的错误组。通过这种方式,您可以更好地控制您的应用程序,并且可以更好地识别代码的弱点。例如:
private void Form1_FormClosing(object sender, FormClosingEventArgs e) {
try{
//Put here your code
}
catch{
}
}
Run Code Online (Sandbox Code Playgroud)
通用的“异常”肯定无法帮助您或用户识别应用程序中可能存在的错误
归档时间: |
|
查看次数: |
6166 次 |
最近记录: |