Catch an Exception thrown by another form

后端 未结 4 1560
无人及你
无人及你 2021-01-19 10:48

I\'m trying to do this:

I\'m creating another form, which in it\'s FormClosed method throws an exception, that should be caught by the main form.

Main Form:<

4条回答
  •  萌比男神i
    2021-01-19 11:07

    You'll be able to do this as follows:

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
    
        private void button1_Click(object sender, EventArgs e)
        {
            Form2 form2 = new Form2(this);
            form2.Show();
        }
    
        public void HandleForm2Exception(Exception ex)
        {
            MessageBox.Show("EXCEPTION HAPPENED!");
        }
    }
    

    and on Form2.cs

    public partial class Form2 : Form
    {
        private Form1 form1;
    
        public Form2(Form1 form1) : this()
        {
            this.form1 = form1;
        }
    
        public Form2()
        {
            InitializeComponent();
        }
    
        private void Form2_FormClosed(object sender, FormClosedEventArgs e)
        {
            try
            {
                throw new Exception();
            }
            catch (Exception ex)
            {
                if(this.form1 != null)
                    this.form1.HandleForm2Exception(ex);
            }
        }
    }
    

提交回复
热议问题