【发布时间】:2021-02-11 05:10:45
【问题描述】:
大家好,我在下一段代码中有一个问题 await Task.Run(() => adapter.Fill(dataTable)); 如果它失败了 try catch 块不处理异常。我怎样才能捕捉到异常?
谢谢。
public async Task<DataTable> GetUsersAsync()
{
using (SqlConnection sqlConnection = new SqlConnection(GetSettingsConenction()))
{
try
{
await sqlConnection.OpenAsync();
string query = "SELECT [dbo].[User].[usr_id] AS \"ID\", [dbo].[User].[usr_alias] AS \"ALIAS\", [dbo].[User].[usr_firstname] AS \"NOMBRE\", [dbo].[User].[usr_lastname] AS \"APELIIDO\", [dbo].[User].[usr_email] AS \"MAIL\", (SELECT [dbo].[UserRole].[uro_name] FROM [dbo].[UserRole] WHERE [dbo].[UserRole].[uro_id] LIKE [dbo].[User].usr_urol_id) AS \"ROL\" FROM [dbo].[User] WHERE [dbo].[User].[usr_deleted] NOT LIKE '1'";
SqlCommand sqlCommand = new SqlCommand(query, sqlConnection);
sqlCommand.CommandType = System.Data.CommandType.Text;
sqlCommand.CommandTimeout = SQL_TIMEOUT_EXECUTION_COMMAND;
SqlDataAdapter adapter = new SqlDataAdapter(sqlCommand);
DataTable dataTable = new DataTable();
await Task.Run(() => adapter.Fill(dataTable));
sqlConnection.Close();
return dataTable;
}
catch
{
sqlConnection.Close();
return null;
}
}
}
打开连接后,我模拟互联网连接丢失,当它填充数据表时出现异常。说超时异常
【问题讨论】:
-
为什么不直接调用Fill呢?你为什么使用任务?
-
if it fails the try catch block does not handle the exception你确定吗?你能发布一个最小的复制吗? -
为什么要显式关闭连接? using 块会为您处理这些问题。如果有错误,为什么要返回 null?这只会隐藏问题,并且与表中没有用户无法区分。仅在您实际将执行分支以执行其他操作的地方捕获异常。
-
如果要在所有路径上执行某些代码,请使用
try/catch/finally -
“try catch 块不处理异常失败”——这是什么意思?你到底看到了什么?