Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi - try finally block is guaranteed by compiler to be executed correctly?

I know this was discussed on other topics also, what I'm asking is exactly the title of this question.

Is there such case when try/finally the finally won't execute?

 try
  //some error here
 finally
  //code that MUST be executed
 end;

I'm not talking about how try..except/finally blocks must be used, I'm just asking if this could happen.

LE: Application.Terminate/unplug your computer are particular cases.

like image 530
RBA Avatar asked Aug 25 '11 14:08

RBA


People also ask

Is finally block always executed?

A finally block always executes, regardless of whether an exception is thrown.

When finally block gets executed always?

The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs.

In which condition finally block is executed?

A finally block is always get executed whether the exception has occurred or not. If an exception occurs like closing a file or DB connection, then the finally block is used to clean up the code. We cannot say the finally block is always executes because sometimes if any statement like System.

In which condition finally block will not be executed?

When the System. exit() method is called in the try block before the execution of finally block, finally block will not be executed.


2 Answers

try..finally guarantees that code in the finally block will execute regardless of any exception occuring in the protected block. This of course doesn't apply if the process is killed before the finally block can execute, e.g. by TerminateProcess or turning the power off. An endless loop in the protected block may also prevent the finally block from executing.

like image 94
Ondrej Kelle Avatar answered Nov 15 '22 09:11

Ondrej Kelle


If the power is lost (for instance, if you unplug the computer and it has no battery and is not connected to a UPS), it is very possible that the finally block will not be run. A major OS or driver malfunction (such as a BSOD) might also cause this. However, the entire idea with the try..finally construct is that the finally block is to be run even if an exception (of any kind) is raised inside the try block. The finally block will even run if there is an exit statement inside try block.

like image 34
Andreas Rejbrand Avatar answered Nov 15 '22 11:11

Andreas Rejbrand