捕获由另一种形式抛出的异常 [英] Catch an Exception thrown by another form

查看:120
本文介绍了捕获由另一种形式抛出的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做到这一点:

我创建另一种形式,它在它的FormClosed方法抛出一个异常,应该由主要形式被抓

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

主要形式:

try
    {
        frmOptions frm  = new frmOptions();
        frm.ShowDialog();                        
    }
catch(Exception)
    {
        MessageBox.Show("Exception caught.");
    }



frmOptions:

frmOptions:

private void frmOptions_FormClosed(object sender, FormClosedEventArgs e)
{
    throw new Exception();
}



调试器停止与该消息异常的:

The debugger stops on the exception with this message:

异常是由用户代码未处理

Exception was unhandled by user code

为什么呢?我赶上在创建它的对象的所有者除外。 ?任何人有一个想法

Why? I'm catching the exception in the owner of the object that created it. Anybody has an idea?

推荐答案

您就可以做到这一点,如下所示:

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

和上Form2.cs

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

这篇关于捕获由另一种形式抛出的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆