Yehezkel
Yehezkel

Reputation: 135

C# winforms doesn't catch exceptions in specific cases

Trying to ask my question again - last time it messed up.

This is my example code:

  1. Little form, that contains only button and combobox:

    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();
    }
    }
    
  2. Project's Program class that calls the question form and handles the exceptions:

     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");
    }
    }
    

Now, when one clicks the button, the event "SelectedIndexChanged" is rise (and the messageBox appear) but the exception is ignored. Only when the user selects manually another index in the combobox, the exception handled.

The question is, how to handle these exceptions too?

Upvotes: 4

Views: 199

Answers (1)

ASh
ASh

Reputation: 35730

could not intercept exception even with try-catch:

try
{
    comboBox1.DataSource = new List<string>() {"a", "b", "c"};
}
catch (Exception ex)
{
}

It seems ComboBox ignores exceptions which happen when DataSource is set:

ListControl.DataSource source code

try 
{
    SetDataConnection(value, displayMember, false);
} catch 
{
    DisplayMember = "";
}

ComboBox.DataSource uses base ListControl implementation

Upvotes: 4

Related Questions