我的函数没有覆盖所有返回路径还是编译器的错误

问题描述 投票:0回答:1

我有以下功能,直到我最近更新 Visual Studio 为止 2022 编译器 (17.11.4)。我从编译器得到的错误是:

not all code paths return a value
。但哪条路没有被覆盖呢?一个是
return GetAllDatesWithoutLock();
,另一个是重投
ExceptionDispatchInfo.Throw(ex);
?这段代码在更新之前一直工作正常。

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");
    }
}
c# exception try-catch-finally
1个回答
0
投票

虽然

ExceptionDispatchInfo.Throw
有一个
DoesNotReturnAttribute
,但这个属性是为了nullable分析,在分析是否所有代码路径都返回时不考虑。就后者而言,你只是调用一个普通的方法。

我只需在 catch 块的末尾添加一个

throw;
语句即可。

catch (Exception ex)
{
    Console.WriteLine(Thread.CurrentThread.Name + "Error occurred.");
    log.Error(Thread.CurrentThread.Name + "Error occurred in GetAllDates:", ex);
    ExceptionDispatchInfo.Throw(ex);
    throw;
}
© www.soinside.com 2019 - 2024. All rights reserved.