我有以下功能,直到我最近更新 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");
}
}
虽然
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;
}