C# – 调用异常时如何获取类名和行号
发布时间:2020-12-15 03:42:48 所属栏目:百科 来源:网络整理
导读:我需要两种方法,一种是从调用异常的方法获取Class,另一种方法得到调用异常的行号. 到目前为止,我有这个代码,它让我的类名和行号一起(例如:DatabaseHandler.cs:line 70): private string GetClassAndLine() { string tempName = e.GetBaseException().ToSt
我需要两种方法,一种是从调用异常的方法获取Class,另一种方法得到调用异常的行号.
到目前为止,我有这个代码,它让我的类名和行号一起(例如: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中以存储发生的任何异常. 更新2: 我正在测试这个代码,有些建议: 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(); } 这是特定的数据库异常返回的.没有线号或类名被触发.我该怎么做? Error was found at Class: Oracle.DataAccess.Client.OracleException. Line Number: 0 我想要的是例如:“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()); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |