如何显示哪个行号导致错误,这是否可能与.NET编译其.exes的方式有关?
如果没有,Exception.Message是否有自动方式显示被淘汰的子?
try
{
int x = textbox1.Text;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
Run Code Online (Sandbox Code Playgroud) 我需要两个方法,一个用于从调用异常的位置获取Class,另一个用于获取调用异常的行号.
到目前为止,我有这个代码,它将类名和行号一起给我(例如:DatabaseHandler.cs:第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);
}
Run Code Online (Sandbox Code Playgroud)
所以如果你有任何想法我怎么能单独得到它们,那将会有很大的帮助.然后将它们传递到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();
}
Run Code Online (Sandbox Code Playgroud)
这是在特定数据库异常时返回的内容.没有行号被触发的行号或类名.我怎么能得到它?
Error was found at Class: Oracle.DataAccess.Client.OracleException. …
Run Code Online (Sandbox Code Playgroud) 我在Visual Studio 2015中创建了一个空白的Universal Windows App项目。
我添加类似:
try {
string foo = null;
int len = foo.Length;
} catch (Exception ex) {
System.Diagnostics.Debug.WriteLine(ex);
}
Run Code Online (Sandbox Code Playgroud)
我得到如下的堆栈跟踪:
Exception thrown: 'System.NullReferenceException' in TestStackTraces.exe
System.NullReferenceException: Object reference not set to an instance of an object.
at TestStackTraces.App.OnLaunched(LaunchActivatedEventArgs e)
Run Code Online (Sandbox Code Playgroud)
即没有行号。
如何显示行号?