当返回值可能未被分配时,为什么会编译?

时间:2013-12-05 16:00:29

标签: c# exception control-flow

在我看来,这段代码:

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块中返回该方法,并且最后一行不会到达,在这种情况下,方法没有返回任何内容?

3 个答案:

答案 0 :(得分:7)

代码将catch(全部)异常,将addSuccess设置为false,然后进入返回行。如果没有抛出异常,返回行将返回true。并且addSuccess在第一行被赋值,它永远不会被取消分配。

答案 1 :(得分:4)

总是会受到回报。你吞下了这个错误。

如果你要抛出异常,那么返回就不会被击中。尽管如此,这是预期的行为。

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

答案 2 :(得分:2)

  

因为无法保证到达返回线

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

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