【发布时间】:2014-04-07 12:55:35
【问题描述】:
我以为我可以在我的项目中捕获另一个类引发的异常,但我一定是做错了。在第一堂课中,我用 try/catch 块包围了我对另一堂课的调用:
try
{
ImportPowerPoint.CreateTitle(textBoxPpt.Text, textBoxPkg.Text);
}
catch (FormatException ex)
{
MessageBox.Show(ex.Message, "ERROR",
MessageBoxButtons.OK,
MessageBoxIcon.Warning);
}
在第二类中,这是我抛出异常的地方:
if (!_layoutMap[(int)Layouts.A].ContainsValue(Fields.Title))
throw new FormatException("Standard (A) Layout does not contain a title.");
if (!_layoutMap[(int)Layouts.A].ContainsValue(Fields.Txt1))
throw new FormatException("Standard (A) Layout does not contain a txt1.");
if (!_layoutMap[(int)Layouts.A].ContainsValue(Fields.Prompt))
throw new FormatException("Standard (A) Layout does not contain a prompt.");
当我运行程序时,它会在抛出异常的地方立即中断,而不是显示我在 try/catch 块中定义的错误窗口。我没有正确处理这个 try/catch 吗?
为了澄清,我通过从我正在解析的 PowerPoint 中删除某些部分来强制发生异常。例如,当程序失败时,因为我删除了Title 字段,抛出的异常类型为 FormatException。我在调用类中的catch 不应该处理这个吗?
编辑:我想我可能已经发现了导致这种情况发生的原因。抛出的异常在另一个线程中。那么,既然它在另一个线程中,这是否意味着这就是我的 try/catch 没有捕获异常的原因?
【问题讨论】:
-
只是为了澄清你是说
ImportPowerPoint.CreateTitle方法抛出了未被捕获的异常吗?因为看起来它应该捕获所有FormatExceptions 并显示您的消息框。 -
实际上,这可能很重要,实际异常是在另一个从
ImportPowerPoint.CreateTitle调用的类中引发的。我在想,无论异常发生在哪里,无论是在立即调用的类中,还是从该类调用的类中,调用类都会捕获异常,如果这有意义的话。 -
如果该方法调用其他类的东西,那么 catch 应该仍然可以捕获。代码在其他类中的事实不是问题(实际上通常是预期的,因为您经常在框架类中捕获异常,而不是您自己的代码)。您确定在这段代码中(并且它没有从代码中的其他地方抛出异常)吗?
-
您可能需要检查您在外部类中捕获的异常的 InnerException 属性。
标签: c# exception-handling