c# - 显示从Windows窗体引发的正确错误消息

标签 c# winforms error-handling

我正在研究Windows Forms应用程序。我有几个try-catch块的构造函数中发生了很多事情。但是,作为最终结果,我想在form_shown事件上显示错误消息。我不确定执行此操作的正确方法是什么。我正在考虑使一个字符串变量从所有形式可见,然后在每个try-catch块中设置不同的消息,该消息将通过调用在我想执行的form_shown事件中显示此字符串变量的值来显示。

但这似乎不是很好的方法。我希望以某种方式重新引发异常或类似的事情,并在form_shown事件中处理它。我认为这更接近正确的错误处理方法。

最佳答案

您违反了两个重要的guidelines:

Do minimal work in the constructor. Constructors should not do much work other than to capture the constructor parameters. The cost of any other processing should be delayed until required.





Do throw exceptions from instance constructors if appropriate. Constructors should throw and handle exceptions like any method. Specifically, a constructor should not catch and hide any exceptions that it cannot handle.



因此,要回答您的问题,如果在构造器阶段出现任何问题,请立即进行显示。这意味着该对象无法构造。

我不知道构造函数中会发生什么事情,但是我很确定您应该将其推迟到稍后的时间,例如表格加载。但仍然:在发生异常的地方显示异常。

关于c# - 显示从Windows窗体引发的正确错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15873191/

相关文章:

c - 如何处理错误

C# 重用 SQLCommand

c# - Regex-如何删除 "and "之间的逗号?

vb.net - 当任何表单关闭时,如何关闭应用程序?

c# - 如何缩短这个通用列表?

c# - 以下方法之间的调用不明确

php - CodeIgniter,了解调用函数的 Controller

c# - TextBlock 绑定(bind)不起作用

c# - 如何从 C# 访问将指针作为输入参数的 C++ 函数

php - 拥有更有效的代码以返回错误