捕获另一个表单抛出的异常 [英] Catch an Exception thrown by another form

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

问题描述

我正在尝试这样做:

我正在创建另一个表单,它在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?

推荐答案

我不认为这可以工作,新的表单不是在你的上面的代码,它只是由它启动。如果你检查stacktrace是否抛出异常,你不应该看到上面的代码,所以它不能捕获异常。

I don't think this can work, the new form is not running in the context of your code above, it is only being launched by it. If you check the stacktrace for the exception thrown you shouldn't see the code above in it, so it can't catch the exception.

更新:我刚刚创建了一个测试项目&试过了堆栈跟踪对于原始形式一无所知。如果您想捕获未处理的异常,您可能需要查看此问题未处理的异常处理程序在.NET 1.1中

Update: I just created a test project & tried it. The stacktrace knows nothing about the original form. If you want to catch unhandled exceptions you may want to check out this question Unhandled Exception Handler in .NET 1.1

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

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