delphilazarusfpc

try except versus try finally in Delphi


Many things have be mentioned for nested exception handling in Delphi or 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
    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');

Solution

  • 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.

    In first version of your code, anything after finally block will not be executed and exception will be propagated to the next level.

    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.

    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