[英]Why is this code outside my “using” statement unreachable?
如果在using語句中拋出異常,它應該立即調用finally
塊,並處置該對象。 所以try
塊的其余部分不應該執行,對吧?
public static async Task<bool> AddCharName(string id, string name)
{
using (var dbConn = new DbConn())
{
await dbConn.Connection.OpenAsync();
command = "UPDATE user SET name = @name WHERE name IS NULL AND id = @id";
using (MySqlCommand update = dbConn.Connection.CreateCommand())
{
update.CommandText = command;
update.Parameters.Add("@name", MySqlDbType.VarChar).Value = name;
update.Parameters.Add("@id", MySqlDbType.VarChar).Value = id;
await update.ExecuteNonQueryAsync();
return true;
}
}
return false;
}
在我的示例中, return false
表示“檢測到無法訪問的代碼”警告。 我是否正確認為這是一個錯誤? 就像我在想如果在using (MySqlCommand upd...
拋出一個錯誤using (MySqlCommand upd...
那么它應該返回false吧?
真的很簡單......
它總是從
return true;
它永遠不會有機會到達
return false;
這是編譯器最了解的情況
更新
你確定嗎? 因此,如果在using語句中發生異常,則在返回true之前它仍將返回true?
盡管using
工具最后嘗試 ,它仍然拋出原始異常,因此仍然永遠不會return false;
(不管發生什么)
事實上, using
語法糖是try-finally,但因為沒有catch塊。 換句話說,你有:
MySqlCommand update = dbConn.Connection.CreateCommand();
try
{
update.CommandText = command;
update.Parameters.Add("@name", MySqlDbType.VarChar).Value = name;
update.Parameters.Add("@id", MySqlDbType.VarChar).Value = id;
await update.ExecuteNonQueryAsync();
return true;
}
finally
{
update.Dispose();
}
注意沒有catch
,因此你的代碼也是:
return true;
並返回那里,或 finally
塊被執行處理對象,然后異常立即冒泡到調用者(如果沒有處理程序則崩潰)。 在任何情況下,執行都不會超過您的return true;
聲明。 外部using
塊也是如此。
現在,您最想要做的是catch
發生的異常。 快速而骯臟的方法是將所有內容包裝在try-catch中,但根據應用程序的不同,您可能希望更細致地了解捕獲內容和方式:
try
{
using (var dbConn = new DbConn())
{
await dbConn.Connection.OpenAsync();
command = "UPDATE user SET name = @name WHERE name IS NULL AND id = @id";
using (MySqlCommand update = dbConn.Connection.CreateCommand())
{
update.CommandText = command;
update.Parameters.Add("@name", MySqlDbType.VarChar).Value = name;
update.Parameters.Add("@id", MySqlDbType.VarChar).Value = id;
await update.ExecuteNonQueryAsync();
return true;
}
}
}
catch (MySqlException)
{
return false;
}
代碼無法訪問,因為您已經return true
。
用try catch
try
{
using (var dbConn = new DbConn())
{
await dbConn.Connection.OpenAsync();
command = "UPDATE user SET name = @name WHERE name IS NULL AND id = @id";
using (MySqlCommand update = dbConn.Connection.CreateCommand())
{
update.CommandText = command;
update.Parameters.Add("@name", MySqlDbType.VarChar).Value = name;
update.Parameters.Add("@id", MySqlDbType.VarChar).Value = id;
await update.ExecuteNonQueryAsync();
return true;
}
}
}
catch (Exception er)
{
return false;
}
它將進入finally塊,但是在finally完成后仍然會拋出異常,因此在這種情況下它將無法返回值。
它顯示是因為如果在使用塊中存在異常,它將首先處置它自己然后它來捕獲塊並且你的return false;
變得無法到達。 我建議將值保存在變量中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.