Search code examples
c#exceptioncontrol-flow

Why does this compile, when the return value could presumably be unassigned?


It seems to me that this code:

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;
}

...should not compile, because there's no guarantee that the return line will be reached - if there's an exception, addSuccess is assigned to, but won't the method return from within the catch block, and the final line not be reached, in which case nothing is returned from the method?


Solution

  • The return will always be hit. You are swallowing the error.

    If you were to throw the exception, then the return would not be hit. Even then though, it's expected behavior.

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