【发布时间】:2013-12-05 16:00:28
【问题描述】:
在我看来,这段代码:
public static bool InsertInventoryItem(DuckbillUtils.InventoryItem invItem)
{
bool addSuccess = true;
try
{
InventoryItemsList invItems = new InventoryItemsList();
invItems.inventoryItems.Add(invItem);
}
catch (Exception)
{
addSuccess = false;
}
return addSuccess;
}
...不应该编译,因为不能保证会到达返回行 - 如果有异常, addSuccess 被分配给,但方法不会从 catch 块内返回,最后一行不会达到,在这种情况下,该方法没有返回任何内容?
【问题讨论】:
-
为什么方法会从 catch 块中返回?那里没有返回声明。该方法将始终返回
addSuccess。 -
您似乎认为 try-catch 意味着方法的结束。它没有,它只是在捕获结束时继续。
-
在方法中设置断点。我敢让你重现一个你没有点击 return 语句的情况:)。
-
@ErikKerber:好的,重置或电源故障 :) 我赢了什么?
-
@AustinSalonen 好的,我们都赢了。它适用于 Xamarin.iOS(我面前有它)。 stackoverflow.com/questions/1599219/…
标签: c# exception control-flow