C # winforms does not rule out exceptions in specific cases

Trying to ask my question again - the last time it went bad.

This is my sample code:

  • A small form containing only a 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();
    }
    }
    
  • Project Programclass that calls the form questionand handles 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, with a single click on the button, the "SelectedIndexChanged" event is incremented (and a MessageBox appears) , but the exception is ignored. Only when the user manually selects another index in the combo box is an exception thrown.

The question is how to handle these exceptions too?

+4
source share
1 answer

:

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

, ComboBox , DataSource:

ListControl.DataSource

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

ComboBox.DataSource ListControl

+4

Source: https://habr.com/ru/post/1671018/


All Articles