C# - Try-Catch-Finally on Return
本问题已经有最佳答案,请猛点这里访问。
我有以下代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | public DataTable GetAllActiveUsers() { DataTable dataTable = new DataTable(); try { connection.Open(); SqlCommand getAllActiveUsersCommand = new SqlCommand(getAllUsers, connection); SqlDataAdapter dataAdapter = new SqlDataAdapter(getAllActiveUsersCommand); dataAdapter.Fill(dataTable); return dataTable; } catch(Exception e) { Console.WriteLine(e); return null; } finally { connection.Close(); } } |
基本上是我数据库中的活跃用户。但有人能向我解释,如果成功运行
谢谢
对。
如前所述:msdn
Typically, the statements of a finally block run when control leaves a
try statement. The transfer of control can occur as a result of normal
execution, of execution of a break, continue, goto, or return
statement, or of propagation of an exception out of the try statement.
但最后一个块并不总是被执行。你可以在这里读到亚历克斯·帕帕迪莫利斯的轶事
始终执行finally块。
您应该在finally块中处理。因为,Dispose也会关闭连接并释放非托管内存资源。
1 2 3 4 | finally { connection.Dispose(); } |
是的。无论您的