C# 在异常处理中显示行号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/688336/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Show line number in exception handling
提问by Crash893
How would one display what line number caused the error and is this even possible with the way that .NET compiles its .exes?
如何显示导致错误的行号,甚至可以通过 .NET 编译其 .exes 的方式实现?
If not is there an automated way for Exception.Message to display the sub that crapped out?
如果没有, Exception.Message 是否有一种自动方式来显示被淘汰的子?
try
{
int x = textbox1.Text;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
采纳答案by Steven A. Lowe
Use ex.ToString()to get the full stack trace.
使用ex.ToString()得到完整的堆栈跟踪。
You must compile with debugging symbols (.pdb files), even in release mode, to get the line numbers (this is an option in the project build properties).
即使在发布模式下,您也必须使用调试符号(.pdb 文件)进行编译以获取行号(这是项目构建属性中的一个选项)。
回答by Mitch Wheat
If you use 'StackTrace'and include the .pdb files in the working directory, the stack trace should contain line numbers.
如果您使用“StackTrace”并在工作目录中包含 .pdb 文件,则堆栈跟踪应包含行号。
回答by Gabriel McAdams
To see the stacktrace for a given Exception, use e.StackTrace
要查看给定异常的堆栈跟踪,请使用e.StackTrace
If you need more detailed information, you can use the System.Diagnostics.StackTraceclass (here is some code for you to try):
如果您需要更详细的信息,可以使用System.Diagnostics.StackTrace类(这里有一些代码供您尝试):
try
{
throw new Exception();
}
catch (Exception ex)
{
//Get a StackTrace object for the exception
StackTrace st = new StackTrace(ex, true);
//Get the first stack frame
StackFrame frame = st.GetFrame(0);
//Get the file name
string fileName = frame.GetFileName();
//Get the method name
string methodName = frame.GetMethod().Name;
//Get the line number from the stack frame
int line = frame.GetFileLineNumber();
//Get the column number
int col = frame.GetFileColumnNumber();
}
This will only work if there is a pdb file available for the assembly. See the project properties - build tab - Advanced - Debug Info selection to make sure there is a pdb file.
这仅在有可用于程序集的 pdb 文件时才有效。查看项目属性 - 构建选项卡 - 高级 - 调试信息选择以确保有一个 pdb 文件。
回答by Ahmed Elzeiny
string lineNumber=e.StackTrace.Substring(e.StackTrace.Length - 7, 7);
回答by Rhushikesh
this way you can Get Line number from Exception
这样你就可以从异常中获取行号
public int GetLineNumber(Exception ex)
{
const string lineSearch = ":line ";
var index = ex.StackTrace.LastIndexOf(lineSearch);
int ln=0;
if (index != -1)
{
var lineNumberText = ex.StackTrace.Substring(index + lineSearch.Length);
string lnum = System.Text.RegularExpressions.Regex.Match(lineNumberText, @"\d+").Value;
int.TryParse(lnum,out ln);
}
return ln;
}

