帮助文档中关于try ... finally的描述,有一段不是很懂
“If an exception is raised but not handled in the finally clause, that exception is propagated out of the try...finally statement, and any exception already raised in the try clause is lost. The finally clause should therefore handle all locally raised exceptions, so as not to disturb propagation of other exceptions.”
以上一段文字摘自Delphi 7 的帮助文档,从中,我得到了一个信息,“在finally 块中要处理异常”,但是Finally 块不是负责释放资源等工作的吗?
[解决办法]
一般这样:
try
try
except
//这里处理异常
end;
finally
//这里释放资源
end;
也有这样的:
try
try
finally
end;
except
end;
看情况吧,异常处理只有通过自己实际运用才能了解一些,不过即使用了,我也还是有一些迷胡。。。
[解决办法]
try
发生异常A
finally
发生异常B
end
在运行的时候,异常B会抛出来,而异常A不会抛,"丢失"了!
The finally clause should therefore handle all locally raised exceptions
这句话是说要处理异常B,比如用try..except把异常B包起来,这样异常A就会抛出来了!
例子:
procedure TForm1.FormCreate(Sender: TObject);var L: TList;begin L := TList.Create; try L.Items[0] := Self;//异常A,下标越界 finally L.Free; Tag := 0;// try Tag := 1 div Tag;//异常B,被0除。如果它没被try..except包起来的话,异常A就不会报,而异常B会!// except//// end; end;end;
[解决办法]
对这段话,我的理解正好跟 lz 反一下。
是说如果 finally 段有异常的话,会替换掉(如果有的话)try 里出现的异常。
不是要在 finally 处理异常,是要保证 finally 里不会再有异常的代码。