故事:我有来自 3 个不同类的 3 个函数。函数调用顺序为:
Form1_Load(...)
-> Student.GetAllStudents(...)
-> StudentDAL.GetStudentInformation(...)
-> ConnectionManager.GetConnection(...)
我想做的是显示最内部函数的 StackTrace,即ConnectionManager.GetConnection()
在Form1 类MessageBox
中。换句话说,我不想在任何内部类中使用,而只想在最外面的类中使用Form1 类。MessageBox
问题:要获取内部异常,我们可以使用InnerException
orGetBaseException()
等,但是当我尝试获取内部异常时,它会抛出异常“对象引用未设置为实例”,这意味着没有内部异常,当我检查时,值为也null
。我只想知道为什么会这样null
?它不应该引用内部异常吗?如我错了请纠正我。
功能代码:
Form1_Load(...)
private void Form1_Load(object sender, EventArgs e) { try { DataTable dt = new DataTable(); dt.Load((**new Student().GetAllStudents()**)); if (dt.Rows.Count <= 0) { MessageBox.Show("Student table empty."); } else { this.dataGridView1.DataSource = dt; } } catch (Exception ex) { MessageBox.Show(ex.Message+Environment.NewLine+"Source(s) : "+ex.StackTrace.Substring(0, ex.StackTrace.LastIndexOf("at"))); }
GetAllStudents(...)
public SqlDataReader GetAllStudents() { try { return StudentInformationDataAccessLayer.GetStudentInformation(); } catch (Exception ex) { throw ex; } }
GetStudentInformation(...)
public static SqlDataReader GetStudentInformation() { try { SqlConnection sqlCon = null; sqlCon = ConnectionManager.GetConnection(); if (sqlCon == null) { return null; } String Query = null; Query = "SELECT * FROM [dbo].[Student]"; SqlCommand cmd = new SqlCommand(Query, sqlCon); SqlDataReader dr = null; dr = cmd.ExecuteReader(CommandBehavior.CloseConnection); return dr; } catch (Exception ex) { throw ex; } }
GetConnection(...)
public static SqlConnection GetConnection() { String _connectionString = null; _connectionString = ConfigurationManager.ConnectionStrings["Default"].ConnectionString; if (_connectionString == null) { return null; } try { SqlConnection connection = new SqlConnection(_connectionString); connection.Open(); return connection; } catch (Exception ex) { throw ex; } }