Search code examples
c#exceptiontry-catch-finally

Doesn't my function cover all return paths or it is compiler's bug


I have the following function that worked until my recent update of the Visual Studio 2022 compiler (17.11.4). The error I get from the compiler is : not all code paths return a value. But which path is not covered? One is return GetAllDatesWithoutLock(); and the other is a rethrow ExceptionDispatchInfo.Throw(ex);? This code was working OK until the update.

public ScheduleDateTimeResponse GetAllDates()
{
    log.Info("GetAllDates before locking");
    semaphoreObject.Wait();
    try
    {
        return GetAllDatesWithoutLock();
    }
    catch (Exception ex)
    {
        Console.WriteLine(Thread.CurrentThread.Name + "Error occurred.");
        log.Error(Thread.CurrentThread.Name + "Error occurred in GetAllDates:", ex);
        ExceptionDispatchInfo.Throw(ex);
    }
    finally
    {
        semaphoreObject.Release();
        log.Info("GetAllDates after locking");
    }
}

Solution

  • Although ExceptionDispatchInfo.Throw has a DoesNotReturnAttribute, this attribute is for nullable analysis, and not considered when analysing whether all code paths return. As far as the latter is concerned, you are just calling an ordinary method.

    I would just add a throw; statement at the end of the catch block.

    catch (Exception ex)
    {
        Console.WriteLine(Thread.CurrentThread.Name + "Error occurred.");
        log.Error(Thread.CurrentThread.Name + "Error occurred in GetAllDates:", ex);
        ExceptionDispatchInfo.Throw(ex);
        throw;
    }