简体   繁体   English

在Delphi中尝试除了尝试还是最终尝试

[英]try except versus try finally in Delphi

Many things have be mentioned for nested exception handling in Delphi or fpc. 对于Delphi或fpc中的嵌套异常处理,已经提到了很多事情。 Something like this for example. 例如这样的事情。 My question, that maybe solves the need for nested try... blocks, is if there is an actual difference between the following 2 versions of code , I don't see any except if an undefined behavior or something occurs after expect or finally ... 我的问题可能解决了对嵌套try...块的需求,是以下两个版本的代码之间是否存在实际差异 ,我看不到任何区别除非未定义的行为或在expectfinally之后发生了什么。 ..

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

and... 和...

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

Yes there is a difference. 是,有一点不同。 Huge one. 巨大的一个。

If there is no exception in try block then both versions will execute all code, but if there is an exception behavior differs. 如果try块中没有异常,则两个版本都将执行所有代码,但是如果存在异常,则行为会有所不同。

In first version of your code, anything after finally block will not be executed and exception will be propagated to the next level. 在您的代码的第一个版本中, 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 

In second version exception will be handled by except block and code following will continue with normal execution. 在第二个版本中,异常将由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

In linked question you have nested exception blocks, and that situation will behave differently than above one, in the way it was explained in answers to that question. 在链接的问题中,您嵌套了异常块,并且这种情况的行为与上一个情况不同,其解释方式与该问题的答案相同。


Documentation: Delphi Exceptions 文档: Delphi异常

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM