【问题标题】:Why does this compile, when the return value could presumably be unassigned? [closed]当返回值可能未分配时,为什么会编译? [关闭]
【发布时间】: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


【解决方案1】:

代码将catch (所有)异常,将addSuccess 设置为false,然后继续返回行。如果没有抛出异常,则返回行将返回 true。而addSuccess 在第一行被赋值,它永远不会被取消赋值。

【讨论】:

    【解决方案2】:

    返回总是会被击中。你正在接受错误。

    如果您要抛出异常,则不会命中返回。尽管如此,这是预期的行为。

    public static bool InsertInventoryItem(DuckbillUtils.InventoryItem invItem)
    {
        bool addSuccess = true;
        try
        {
            InventoryItemsList invItems = new InventoryItemsList();
            invItems.inventoryItems.Add(invItem);
        }
        catch (Exception)
        {
            throw;
        }
        return addSuccess;
    }
    

    【讨论】:

      【解决方案3】:

      因为无法保证会到达返回线

      在提供的代码中看起来不像这样。

      try/catch 将捕获代码中的所有(可能捕获的)异常。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-23
        • 1970-01-01
        • 2016-08-23
        • 2020-04-06
        • 2011-09-28
        • 1970-01-01
        相关资源
        最近更新 更多