views:

384

answers:

2

PHP has no finally block - i.e., whereas in most sensible languages, you can do:

try {
   //do something
} catch(Exception ex) {
   //handle an error
} finally {
   //clean up after yourself
}

PHP has no notion of a finally block.

Anyone have experience of solutions to this rather irritating hole in the language?

+5  A: 

Solution, no. Irritating cumbersome workaround, yes:

$stored_exc = null;
try {
    // Do stuff
} catch ($exc) {
    $stored_exc = $exc;
    // Handle an error
}
// "Finally" here, clean up after yourself
if ($stored_exc) {
    throw($stored_exc);
}

Yucky, but should work.

Mihai Limbășan
So what you're saying is PHP does have finally... it's spelled "if"
Max Schmeling
What happens if I return within the try{}? Your `if` won't execute.
Rob
That's easy, don't return within the try{}. In case you didn't notice, I specifically pointed out in the very first sentence that it's not a solution but an irritating, cumbersome workaround. The lack of a finally block cannot be worked around completely since providing a finally guarantee requires interpreter support.
Mihai Limbășan
Oh, in case it came across wrong - good call in the comment, +1 :)
Mihai Limbășan
I admit I am not an expert try/catch/finally user, but why not just throw the exception inside the catch block? is it because you might run some other code PRIOR TO the throw() as cleanup code? And, if (as Rob says) you have a 'return X;' inside the try block, will other language still run the finally block before returning (if so, that's pretty nice, although when I see a return statement, I make assumption nothing else runs after that? Very interesting stuff to me though.
OneNerd
@OneNerd: Yes, other languages will run the finally block even when returning from inside the catch block. They will run it even if you throw inside the catch block. They will obviously not run it if your program dumps code, is killed, if the oerating system crashes, if the power is cut, etc
Mihai Limbășan
A: 

As this is a language construct, you won't find an easy solution for this. You can write a function and call it as the last line of your try block and last line before rethrowing the excepion in the try block.

Good books argues against using finally blocks for any other than freeing resource as you can not be sure it will execute if something nasty happens. Calling it an irritating hole is quite an overstatement. Believe me, a hell lot of exceptionally good code is written in languages without finally block. :)

The point of finally is to execute no matter if the try block was successfull or not.

Csaba Kétszeri