[英]How to print line number where object reference occurred
I need a suggestion regarding Object reference issue. 我需要有关对象引用问题的建议。 I got this message ExceptionMessage: Object reference not set to an instance of an object. 我收到此消息ExceptionMessage:对象引用未设置为对象的实例。 (because some null object) I am printing the stack trace when an error occurs: (由于一些空对象)发生错误时,我正在打印堆栈跟踪:
Exception systemException = lastError.GetBaseException();
By using ex.Message I am able to get the method where exception has occurred but I am not getting any information regarding the line (of that method) where exception occurred. 通过使用ex.Message,我可以获取发生异常的方法,但是我无法获取有关发生异常的(该方法的)行的任何信息。 I need to know at which line object reference has occurred and which object was null when this exception came. 我需要知道发生此异常时在哪个行对象引用发生了,哪个对象为null 。
You need the actual stacktrace: 您需要实际的堆栈跟踪:
systemException.StackTrace
If you want the line numbers, you will need to do something like this: 如果需要行号,则需要执行以下操作:
StackTrace st = new StackTrace(systemException, true);
StackFrame[] frames = st.GetFrames();
foreach(StackFrame frame in frames)
frame.GetFileLineNumber();
That line number is pretty much guaranteed to be in the stack trace. 该行号几乎可以保证在堆栈跟踪中。 If you want to drill down on it, put a try-catch in the large block of code where it might be happening and drop a breakpoint on the catch block, which will allow you to drop down through the InnerExceptions inside of visual studio (if any exist). 如果要对其进行深入研究,请将try-catch放在可能发生的大代码块中,然后在catch块上放置一个断点,这将使您可以在Visual Studio内部通过InnerExceptions进行下拉(如果任何存在)。
Maybe this helps 也许这有帮助
class Program
{
static void Main(string[] args)
{
try
{
string a = null;
a.ToString();
}
catch (Exception ex)
{
var s = ex.StackTrace;
Console.WriteLine(ex.Source);
int st = s.LastIndexOf("line");
Console.WriteLine(s.Substring(st, s.Length - st));
}
}
}
Edited : 编辑:
And yes I just learned, using StrackTrace in the answer posted by EkoostikMartin. 是的,我刚刚在EkoostikMartin发布的答案中使用StrackTrace进行了学习。 I think it is a better answer. 我认为这是一个更好的答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.