PHP5.5: Try/Catch/Finally
Exception handling is available in PHP since version 5. It allows you to have a more fine-grained control over code
when things go wrong ie, when exceptions occur. But since PHP 5.5, exception handling has finally evolved into what it
should have been from the beginning: the finally part has been implemented.
Let’s start with a simple example on what finally actually does:
{% highlight php startinline=True %}{% raw %}
getMessage() . "\n"; } finally { print "Finally, some cleanup!\n"; } } try { foo(); } catch (RuntimeException $e) { print "outer exception: " . $e->getMessage() . "\n"; } finally { print "Outer finally\n"; } /* Output: Try block Finally, some cleanup! outer exception: foobar! Outer finally */ {% endraw %}{% endhighlight %} Do you see how the finally block of the outer loop also gets called? So as said before, the finally part allows you do to (local) cleanups that are actually part of the current try/catch block. They keep code neatly grouped together. ## Finally and return: all bets are off I told you that a finally block will always be called, whether or not an exception has been thrown. But what would happen if we issue a `return` statement inside our try block? Surely, the finally block will not be called, since we are returning from the function? Well, actually, the finally STILL gets called before returning. This is where some weird internal exception magic comes in, that will postpone the return, do the finally block first, and then return. If you think using goto can seriously mess up your workflow, try returning in try/catch/finally blocks :) Again, an example: {% highlight php startinline=True %}{% raw %}