Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When and why can `finally` be useful?

PHP 5.5 has implemented finally to try-catch. My doubt is: when exactly try-catch-finally that might be more helpful than just I write below try-catch?

Example, difference between:

try { something(); }
catch(Exception $e) { other(); }
finally { another(); }

Instead of, just:

try { something(); }
catch(Exception $e) { other(); }
another();

Can send me some example that is common to this case?

Notes:

  1. I talk about try-catch-finally, and not about try-finally, only;
  2. There are some "features" cool, like you cancel current exception and throw a new-other-exception on finally (I don't tried, I read here). I don't know if it is possible without finally;
  3. Would not be more useful something like notcatch? So I can run a code if try goes without an exception. hehe
like image 503
David Rodrigues Avatar asked Mar 23 '14 21:03

David Rodrigues


1 Answers

The code within the finally block is always executed after leaving from either try or catch blocks. Of course you may continue writing code after the try-catch and it will be executed as well. But finally could be useful when you'd like to break out of code execution (such as returning from a function, breaking out of a loop etc.). You can find some examples on this page - http://us2.php.net/exceptions, such as:

function example() {
  try {
     // open sql connection
     // Do regular work
     // Some error may happen here, raise exception
  }
  catch (Exception $e){
    return 0;
    // But still close sql connection
  }
  finally {
    //close the sql connection
    //this will be executed even if you return early in catch!
  }
}

But yes, you are right; finally is not very popular in everyday use. Certainly not as much as try-catch alone.

like image 50
gat Avatar answered Sep 30 '22 19:09

gat