我正在研究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/