我有一个从字典中弹出元素的函数,如果出现任何问题,应该抛出异常。代码看起来相当不错。
type
ENoSuchElementException = class(Exception);
var
FResults: TDictionary<Cardinal, TObject> = TDictionary<Cardinal, TObject>.Create;
FLock: TCriticalSection = TCriticalSection.Create;
/// <exceptions cref="ENoSuchElementException">Element does not exist</exceptions>
function Take(Id: Cardinal): TObject;
begin
FLock.Acquire;
try
try
Result := FResults[Id]; // here may throw exception
FResults.Remove(Id);
except
on E: Exception do
begin
raise ENoSuchElementException.Create(E.ToString);
end;
end;
finally
FLock.Release;
end;
end;
但是 Delphi XE4 编译器提示 W1035:函数“Take”的返回值可能未定义
。
我突然很困惑。如果抛出异常,为什么代码仍然期望返回值?这是否意味着 try...finally
会吃掉异常?有人能指出我的代码有问题吗?
已解决:正如 David 提到的,try... except
应移至外部。谢谢!
最佳答案
David Heffernan 为您提供了最直接的答案,但是另一种方法是完全避免 try
/ except
block 并使用 TryGetValue
方法TDictionary
的。更进一步,如果您还想摆脱单独的锁定对象,您可以:
var FResults: TDictionary<Cardinal, TResult>;
function Take(Id: Cardinal): TResult;
begin
TMonitor.Enter(FResults);
try
if FResults.TryGetValue(Id, Result) then
FResults.Remove(Id)
else
Abort;
finally
TMonitor.Exit(FResults);
end;
end;
TMonitor
历史上存在重大错误,但在 XE4 中不会有问题。
关于delphi - W1035 : Return value of function 'Take' might be undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21351738/