try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
var a = reader.GetString(1);
var b = reader.GetString(3);
var c = reader.GetString(4);
var d = reader.GetString(5);
await context.PostAsync($" ### Please find below the fleet policy information \n #### Policy number - " +
$"`{a}` \n #### Policy type - `{b}` \n #### Property - `{c}` \n #### Number - `{d}` ");
}
}
else
{
await context.PostAsync($"Fleet policy with number **{policyNum}** not found");
}
}
catch (SqlException ex)
{
await context.PostAsync("cannot connect to database");
}
finally
{
conn.Close();
PromptDialog.Confirm(context, afterOkAsync, "You still want to check fleet policy?", "Didn't get that, Please select either yes or no", promptStyle: PromptStyle.PerLine);
}
如果数据库连接不成功,我希望代码捕获异常,但它不起作用。请问代码有什么问题?所有其他人都在工作,但我也对捕获无法连接数据库异常感兴趣
答案 0 :(得分:0)
如果数据库连接不成功,则可能会出现与SqlException不同的异常。只有在抛出SqlException时才会捕获。
您可以在下面找到SqlConnection.Open的例外列表:
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.open(v=vs.110).aspx