再试一次问我的问题 - 上次搞砸了。
这是我的示例代码:
小形式,仅包含按钮和组合框:
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”将上升(并显示messageBox)但将忽略该异常。只有当用户手动选择组合框中的另一个索引时,才会处理异常。
问题是,如何处理这些例外呢?
答案 0 :(得分:4)
也无法拦截异常:
try
{
comboBox1.DataSource = new List<string>() {"a", "b", "c"};
}
catch (Exception ex)
{
}
似乎ComboBox忽略了设置DataSource时发生的异常:
ListControl.DataSource source code
try
{
SetDataConnection(value, displayMember, false);
} catch
{
DisplayMember = "";
}