简体   繁体   English

C#MessageBox错误消息

[英]C# MessageBox Error Messages

In my application I am using message boxes to display error information. 在我的应用程序中,我使用消息框来显示错误信息。

try
{
   // Something...
}
catch (SystemException ex)
{
   MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

This was fine at first, but as my program grows it becomes increasingly difficult to find the try-catch block where this error is generated. 起初这很好,但随着程序的增长,找到生成此错误的try-catch块变得越来越困难。 Is there a way to display the line of code or function in which the error was generated? 有没有办法显示生成错误的代码行或函数? I am using Microsoft Visual C# 2008 Express Edition. 我使用的是Microsoft Visual C#2008 Express Edition。 Thanks. 谢谢。

这将为您提供有关导致错误的方法(堆栈跟踪)的大量信息

MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

Just display the Exception.StackTrace . 只需显示Exception.StackTrace It will contain all kinds of helpful info that should help you find the offending line of code. 它将包含各种有用的信息,可以帮助您找到有问题的代码行。

There is Exception.StackTrace , which is often a bit much for a message box. Exception.StackTrace ,对于消息框来说通常有点多。 Also Exception.TargetSite.Name should be helpful too. Exception.TargetSite.Name应该有用。

you want to review the ex.StackTrace() which will give you full details of the location of the thrown exception. 你想查看ex.StackTrace(),它将为你提供抛出异常位置的完整细节。 You might want to also check the InnerException. 您可能还想检查InnerException。

Why don't you add some extra information to the error message to allow you to find it more easily? 为什么不在错误消息中添加一些额外信息以便更容易找到它? You could add some more text after the "Error" string depending on where abouts the message box is being created. 您可以在“错误”字符串后添加更多文本,具体取决于创建消息框的位置。

The exception that is thrown contains several functions to allow you to get a more detailed explanation of an error. 抛出的异常包含几个函数,以便您可以获得有关错误的更详细说明。

There are a few options that you have available to you. 您可以使用几种选项。

  1. Put something in your message box if you want to give context information 如果要提供上下文信息,请在消息框中添加内容
  2. Show the stack trace information, if on a debug build line numbers will be included 显示堆栈跟踪信息,如果在调试构建中,将包含行号

However, I would caution around this practice, if you are finding that you are getting too many and you can't figure out where, I would start to look at re-structuring your code to ensure that you don't have issues. 但是,我会对这种做法提出警告,如果你发现自己太多而且无法弄清楚在哪里,我会开始考虑重构你的代码以确保你没有问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM