2016-04-16 32 views
1

在Delphi或fpc中嵌套异常处理有许多事情需要提及。例如,像this。我的问题,也许解决了嵌套try...块的需要,是如果有以下2个版本的代码之间的实际差异,我没有看到任何除了如果一个未定义的行为或某事expectfinally后发生...尝试除了最后在Delphi中试用

try 
    StrToInt('AA'); 
finally 
    writeln('I absolutely need this'); 
end; 
writeln('and this'); 

和...

try 
    StrToInt('AA'); 
except 
end; 
writeln('I absolutely need this'); 
writeln('and this'); 

回答

8

是有一个DIF ference。巨大的。

如果在try块中没有异常,那么两个版本都会执行所有代码,但是如果有异常行为会有所不同。

在代码的第一个版本中,finally块之后的任何内容都不会执行,并且异常将传播到下一个级别。

try 
    StrToInt('AA'); // if this code throws exception and it will 
finally 
    writeln('I absolutely need this'); // this line will execute 
end; 
writeln('and this'); // this line will not execute 

在第二版本异常将通过except块和代码以下将继续正常执行处理。

try 
    StrToInt('AA'); // if this code throws exception and it will 
except 
end; 
writeln('I absolutely need this'); // this line will execute 
writeln('and this'); // this line will also execute 

在链接的问题,你有嵌套异常块,那情况会不同的表现比一个上面,在它是在回答这个问题解释的方式。


文档:Delphi Exceptions

+0

还没有看到在文档中。因此,在'try..finally'模块中,当'finally'结束时,控制跳出函数,** if *且只有*如果在'try'中引发异常。感谢您清除此。 – Vassilis

+0

它被记录。你在读什么? –

+0

您的意思是? “如果在finally子句中引发异常,但没有处理该异常,那么**将异常**传播出try ... finally语句......”。我希望这个讨论不是我英语不好的结果! – Vassilis