C#-如何在调用异常时获取类名和行号 [英] C# - How to get Class Name and Line Number when an Exception is called
问题描述
我需要两种方法,一种用于从调用异常的位置获取Class,另一种用于获取调用异常的行号.
I need two methods, one for getting the Class from where the exception was called, and another one which gets the line number where an exception was called.
到目前为止,我已经有了这段代码,该代码将类名和行号结合在一起(例如:DatabaseHandler.cs:line 70):
So far I have this code, which gets me the Class Name and Line Number together (example: DatabaseHandler.cs:line 70):
private string GetClassAndLine()
{
string tempName = e.GetBaseException().ToString();
int tempPosition = 0;
int length = tempName.Length;
for (int i = 0; i < length; i++)
{
if (tempName.ElementAt(i).Equals('\\'))
{
tempPosition = i + 1;
}
}
return tempName.Substring(tempPosition, length - tempPosition);
}
因此,如果您有任何想法我将如何单独获得它们,将大有帮助.然后将它们传递到Oracle中,以存储发生的任何异常.
So if you have any ideas how I could get them individually, it would be of great help. These are then passed into Oracle to store any exceptions which occur.
更新2:
我正在按照某些建议测试此代码:
I am currently testing this code, as some suggested:
private string GetClassName()
{
System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(e, true);
return trace.GetFrame(0).GetMethod().ReflectedType.FullName;
}
private int GetLineNumber()
{
System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(e, true);
return trace.GetFrame(0).GetFileLineNumber();
}
这是在特定数据库异常时返回的内容.没有行号或类名被触发的地方.我该怎么办?
This is what was returned at a particular Database Exception. No Line Number or Class Name where it was triggered. How can I get that?
Error was found at Class: Oracle.DataAccess.Client.OracleException.
Line Number: 0
我想要的例如:"Class:Logging.cs,第57行"
What I want is for Example: "Class: Logging.cs, Line: 57"
谢谢,瑞安
推荐答案
您可以这样做
try
{
// Some code that can cause an exception.
throw new Exception("An error has happened");
}
catch (Exception ex)
{
System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
Console.WriteLine(trace.GetFrame(0).GetMethod().ReflectedType.FullName);
Console.WriteLine("Line: " + trace.GetFrame(0).GetFileLineNumber());
Console.WriteLine("Column: " + trace.GetFrame(0).GetFileColumnNumber());
}
这篇关于C#-如何在调用异常时获取类名和行号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!