4
试图再次问我的问题 - 上次它搞砸了。C#winforms不会在特定情况下捕获异常
这是我的示例代码:
小的形式,即只包含按钮,组合框:
public partial class question : Form { public question() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { comboBox1.DataSource = new List<string>() { "a", "b", "c" }; } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { MessageBox.Show("In comboBox1_SelectedIndexChanged"); throw new Exception(); } }
项目的
Program
类调用question
形式和处理异常:class Program { static void Main(string[] args) { try { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // Add the event handler for handling UI thread exceptions to the event. Application.ThreadException += new ThreadExceptionEventHandler(MyCommonExceptionHandlingMethod); // Set the unhandled exception mode to force all Windows Forms errors to go through // our handler. Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); // Add the event handler for handling non-UI thread exceptions to the event. AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); Application.Run(new question()); } catch (Exception ex) { Console.WriteLine(ex.Message + "3"); } } private static void MyCommonExceptionHandlingMethod(object sender, ThreadExceptionEventArgs t) { Console.WriteLine(t.Exception.Message + "1"); } private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { Console.WriteLine(((Exception)e.ExceptionObject).Message + "2"); } }
现在,当点击按钮时,事件“SelectedIndexChanged”上升(并且出现消息框)但是该例外被忽略。只有当用户手动选择组合框中的另一个索引时,才会处理异常。
问题是,如何处理这些异常呢?
设我明白这一点。您的基于控制台的应用程序和winForm是两个独立的应用程序,并且您想从基于控制台的应用程序运行winFrom应用程序 - 是吗? –
@YawarMurtaza谢谢。不是两个分开的应用程序。只是应用程序的主要部分是控制台应用程序(实际上总是这样)。没关系。 – Yehezkel
好的 - 我已经创建了你的代码的确切副本。运行时永远不会到达“Console.WriteLine(ex.Message +”3“);”声明无论在winForm中做了什么。必须与Application.Run()方法有关,它会在Main方法运行的同一线程上为winForm应用程序创建一个新的消息循环。让我看看在这种情况下是否可以找到异常情况。 –