php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #32100 Request 'finally' support for exceptions
Submitted: 2005-02-25 07:07 UTC Modified: 2012-09-01 07:00 UTC
Votes:11
Avg. Score:4.8 ± 0.6
Reproduced:10 of 10 (100.0%)
Same Version:6 (60.0%)
Same OS:5 (50.0%)
From: ceefour at gauldong dot net Assigned: laruence (profile)
Status: Closed Package: *General Issues
PHP Version: 5.* OS: *
Private report: No CVE-ID: None
 [2005-02-25 07:07 UTC] ceefour at gauldong dot net
Description:
------------
PHP 5 has specifically decided not to support 'finally'. Why?

This is one of numerous cases why finally is useful:

mysql_query("LOCK TABLES mytable WRITE");
try {
  // ... do lots of queries here
} finally {
  mysql_query("UNLOCK TABLES");
}

You need to use UNLOCK TABLES otherwise your tables won't get unlocked when an exception is thrown. This is especially bad if you use persistent connections.

It is possible to emulate finally using try/catch but this introduces code redundancy and may create inconsistent code:

mysql_query("LOCK TABLES mytable WRITE");
try {
  // ... do lots of queries here
  mysql_query("UNLOCK TABLES");
} catch(Exception $e) {
  mysql_query("UNLOCK TABLES");
  throw $e;
}



Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2005-02-25 19:58 UTC] helly@php.net
We've had long discussions and came to the only conclusion that we don't need that, for more search the mailing list archieves.

Besides the following is absolutley equivalent:
mysql_query("LOCK TABLES mytable WRITE");
try {
  // ... do lots of queries here
} catch (Exception $e) {
  // do nothing here
}
 mysql_query("UNLOCK TABLES");

The only difference is the second example does rethrow the exception. Though this is still possible (however much more to type) it is wrong design. Since obviously you are using the exceptions as control flow. 

And that design looks like Java where it unlike with PHP makes somewhat sense.
 [2005-02-25 20:27 UTC] ceefour at gauldong dot net
I don't think the code is absolutely equivalent. And omitting the rethrow statement gives up the whole notion of 'finally'.

Actually my code was trying to *emulate* finally. But it's not the right thing to do. Finally should not even touch the Exception at all... Finally doesn't even know there is an exception.

I have to agree that 'finally' is not _required_ by PHP, but not by 'we'. 'We' in this sense refers to 'all PHP developers' and that includes me, and I _need_ (although not _require_) this functionality. Almost the same as namespaces don't have to be in PHP but some people feel the need for it. However namespaces are much harder to implement yet I think finally is relatively straightforward since we can already emulate it using try/catch, but with the quirks.

I don't think finally is a control flow block. By emulating finally using try/catch, yes maybe, but we have no other choice. Finally is not a control flow because why..? Finally has no idea whether it is inside an Exception or not, and cannot handle it i.e. it's not able to _control_ processing based on the state of Exception. In this sense finally is unconditional, just like ordinary statements but they're also executed when Exception occurs.

IMHO Java has no responsibility here, I think exceptions, try, catch, finally, are fully the domain of Object Oriented [Design &] Programming. Delphi, C++Builder, C++, etc. has it, not just Java.

And even if it does, 'design' is out of the scope of PHP. PHP is a programming language, not a design tool. PHP isn't strictly procedural and also isn't strictly object-oriented. It's just a matter of taste. "Be conservative with what you emit and be liberal with what you accept" and everyone's going to be happy.
 [2010-03-31 12:40 UTC] a dot e at inne dot pl
Could finally also mean that 'returns' will be executed after the finally block

try{
   some ifs
   ...
   return x
   ...
   more ifs
   ...
   throw
   ... 
   return y
}catch{
   handle exceptions
}finally{
   No matter if there was exception or not
   execute this bit before you leave the method.
   For example if object has some state it might be necessary to 
   make sure its consistent at the end
}

In the case i have now at work i had to add method call before every return and throw to make sure that my data will be set properly before method ends.

Would that be a feature someone might like?

thanks

art
 [2010-06-16 20:54 UTC] orlandu96 at gmail dot com
are there any updates on this issue?
 [2010-06-27 00:59 UTC] thuejk at gmail dot com
>We've had long discussions and came to the only conclusion that we don't need 
that, for more search the mailing list archieves.

Where is that discussion? I haven't been able to find it. Only people saying 
that finally is utterly useless, without showing any signs that they have 
actually considered finally's uses.

As the other comments have said, sometimes some code inside a try will allocate 
a non-php ressource which need to be deallocated whether or not an exception is 
thrown. To avoid writing that code twice, you need it in finally.

Version without finally:

try {
   allocate non-php resource
} catch ($ex) {
   deallocate non-php resource
   throw $ex;
}
deallocate non-php resource

Version with finally:

try {
   allocate non-php resource
} finally {
   deallocate non-php resource
}

The finally code is obviously "better". And it is a completely reasonable way to 
code.

Sure you can emulate finally with more code, but so can a Turin Machine. finally 
is syntactic sugar which makes it easier to write maintainable programs.
 [2010-08-16 12:42 UTC] torsten dot landmann at bauermedia dot com
I also agree: 'finally' is needed. I really don't get why it has been left out.

There is no elegant equivalent, especially so since rethrowing the exception alters file and line number saved in the exception, so later it's hard to find out where it originally came from.

Please offer "finally". Don't worry, nobody will be forced to use it.
I definitely will.

thuejk showed very well how 'finally' helps with keeping your code clean. Or vice versa: How the absence of it often causes the need to copy and paste code (which is always a bad development pattern).
 [2010-09-07 17:38 UTC] michael202 at gmx dot de
I also think that try-finally is useful.
try catch is no elegant replacement. 
Just needed it today again.
finally is more elegant than an other solution.

For example:

try {
  lots o' code
  if a return
  ..
  if b exit
  ..
} finally
  do somethin
}

Another solution to the "finally" problem is to use goto.
Not so elegant but not a bad thing according to Knuth.
 [2010-09-09 02:39 UTC] phplasma at gmail dot com
A finally block would indeed be useful, please reconsider.
 [2010-09-09 09:32 UTC] 128bitencrypted at gmail dot com
I noticed this bug because I have exactly the same problem atm and finally could solve it. I found a great discussion about the "return" problem and how it's solved in java. (IMHO I think that's the right way)
stackoverflow dot com/questions/65035/in-java-does-return-trump-finally

In PHP it could be implemented like the following:

function example1()
{
   try {
      return "Return\n";
   } finally {
      echo "Finally\n";
   }
}

echo example1();

Output:
 Finally
 Return

And it's important that finally has the right to overwrite return. (Although I think that there only a few cases where that would be useful)

function example2()
{
   try {
      return "Return wins\n";
   } finally {
      return "Finally wins\n";
   }
}

echo example2();

Output:
 Finally wins

I hope that helps a bit more why finally would be a very useful in php!
Thanks.
 [2010-09-21 09:47 UTC] c891652 at bofthew dot com
I feel nothing but disappointed that this bug got closed, without "any" reason being written in the comments.
I also stand for including "finally". It's a well known Exception Handling control block, and others in this bug have shown clearly why it is needed.
 [2010-10-03 07:58 UTC] matsubokkuri+php at gmail dot com
> c891652 at bofthew dot com
I'm disappointed about this request is closed without critical reasons.

The first comment author doesn't understand OOP correctly. The code cannot raise 
exception to upper class.

The code would be following without finally statement.

// create temporary file
try{
  // write to temporary file
}catch(ConnectionException $e){
  // delete temporary file
}
// delete temporary file

The "delete temporary file" sentence would be duplicate.

I can write with finally as following without duplicate "delete temporary file".
// create temporary file
try{
  // write to temporary file
}finally{
  // delete temporary file
}
 [2010-12-10 12:02 UTC] joshuaswift at gmail dot com
Please add a finally block for exception handling
 [2010-12-10 16:08 UTC] marcus at lastcraft dot com
Hi...

The lack of finally causes us some crufty hard to debug code. The comment about swallowing the source of the exception is not an academic one - I've had grief over this.

As for exceptions being used for "control flow" - they are control flow, that's the whole point. There is an antiquated argument from the C++ era about this, mostly driven by outdated performance data. Exceptions are not the same as errors, being more akin to a continuation when the usual return path does not make sense.

Please, plase add finally to PHP as Java did to C++.

yours, Marcus
 [2010-12-10 23:22 UTC] btsai at vrwarp dot com
Wouldn't the argument against finally from Bjarne Stroustrup's C++ Style and Technique FAQ (http://www2.research.att.com/~bs/bs_faq2.html#finally) hold true?

Basically, most good uses of finally are used for deallocating resources. Another way would simply be to design an object that represents the resource that automatically deallocates itself via the destructor.
 [2011-02-17 14:14 UTC] hardyanto dot donny at gmail dot com
"finally" is very useful for using ADODB:

$db->StartTransaction();
try{
  ....
  ... any exception can occur here...
  ....
} finally {
  $db->CompleteTrans();
}

Even there is exception occur in try block, the CompleteTrans() always be 
called.
 [2011-02-17 16:54 UTC] tyra3l at gmail dot com
+1 for adding the feature.
I'm a little bit disappointed that there are no comment from the php core contributors on this issue except helly, and he didn't the first which closed the, I could accept the fact, that this cannot be done by technical reasons, but AFAIK it was rejected, because the core devs at that time didn't used or understood the finally, so they said, that nobody needs that.

http://marc.info/?l=php-internals&m=96773381231437&w=2

times has changed, try doesn't leaks memory nowdays (or does it?), people got smarter, machines faster, maybe we could reconsider this feature, and reject it based on the current situation, not from a vague discussion from 10 years ago.

Tyrael
 [2011-02-17 17:09 UTC] tyra3l at gmail dot com
sorry, I screwed up part of my comment when editing:
"and he didn't the first which closed the"
and he didn't explained in his comment why is it rejected, aside the fact that we (who?) dont't need it

Tyrael
 [2011-02-17 22:02 UTC] attila dot m dot magyar at gmail dot com
I agree with the previous comments, a 'finally' keyword would be nice and useful when it fits to the conventions and standards applied in a project. If it's not hairy to implement and wouldn't introduce instability in the core, I'd reassure PHP developers to add this feature in a future release.

Best regards,
Athos
 [2011-02-19 17:34 UTC] gunter at web dot com
++ for finally in PHP.
 [2011-03-20 10:44 UTC] php at techdp dot co dot uk
+++ for finally in PHP. It is one of the most elegant and expressive keywords in modern programming, allowing precise capture of error handling semantics, and easy authorship of bug-free code!
 [2011-04-05 21:16 UTC] adam dot pippin at ohmedia dot ca
---
Disable user permission checking
try
{
   Call a half a dozen methods
}
finally
{
   Re-enable user permission checking
}
---

The ten year old discussion I found on the issue (http://marc.info/?l=php-internals&m=96774165717219&w=3) doesn't seem terribly applicable to my case. Specifically, it suggests:

---
try {
         ... modify contents ...
} catch {
         ... any error recovery code here ...
}
... cleanup code ...
---

Except my code doesn't 'recover' from errors. It runs back up the call stack and reports the error to the user. I have absolutely zero use for a catch here. My workaround (which, unlike a basic rethrow preserves the line/file):

---
Disable permission checking
try
{
   Run methods
}
catch (Exception $e)
{
   Enable permission checking
   throw new Exception($e->getMessage(), $e->getCode(), $e);
}
Enable permission checking
---

The workaround simply requires a few extra lines of code and a bunch of duplicated code. But hey, finally isn't required, so it's all good.
 [2011-05-05 11:52 UTC] ealexs at gmail dot com
PHP++ for finally in PHP ;)

my code:

disableSIPTrunk (10 lines of code)

try
{
    // do some stuff 
}
finally 
{
    enableSIPTrunk (10 lines of code)
}

// saves duplicate code and it's very elegant !
 [2011-05-30 02:53 UTC] bat at flurf dot net
Here's an idea! Find all the people who think "finally" isn't needed in PHP.  Invite them to go back to programming Visual Basic, because they're ignorant.  The rest can work on implementing it.  Easy!
 [2011-07-22 07:53 UTC] dsberliner at gmail dot com
++ for finally in exception handling. Please reconsider.
 [2011-07-25 03:27 UTC] ninzya at inbox dot lv
++finally
 [2011-09-07 14:49 UTC] viktor at zuiderkwast dot se
The same problem exists in C++, which also lacks the finally clause. The standard way to solve the resource allocation problem in C++ is instead by using the RAII design pattern.

As noted in Wikipedia on RAII, "In this language, the only code that can be guaranteed to be executed after an exception is thrown are the destructors of objects residing on the stack.". The same is valid for PHP (although the objects are reference-counted instead of being allocated on the stack). The destructor is guarranteed to be called as soon as all references to the object run out of scope, so the RAII is effectively usable in PHP.

So, the code you would put in the finally clause in Java etc has to be put in a destructor of some object instead. Then, when a return or a or an uncatched exception occurs inside a try block, and there are no other references to the object, the destructor will be called at this point to free the resources.

In my optinion, the finally clause is a more elegant solution, although it might be *too sophisticated* for PHP...
 [2011-11-18 00:25 UTC] chiestand at salk dot edu
First, thank you everyone who has contributed to this bug report thread. Your 
insights have been incredibly useful.

I too vote for inclusion of "finally" into PHP. In my own particular situation I was 
able to solve my problem using Stroustrup's RAII pattern (thank you btsai). But I can 
imagine that in some cases creating a class for every resource used might be 
inconvenient.

I think ceefour really summed it up nicely back in 2005 with even more-ancient 
wisdom: "Be conservative with what you emit and be liberal with what you accept". 
Provide the tool, and let the coder decide what pattern to use.
 [2011-12-05 15:53 UTC] topaz dot php dot bugs at lt3 dot us
Ugly workaround hack time!

(This is not a substitute for a real language feature!)

Mix and match with try/catch blocks as necessary.

<?php

// Usage examples

// With no lambda functions <5.3, we do this instead :(
function example_finally()
{
  print "Finally was called!\n";
}

function example1()
{
  $finally = new Finally("example_finally");
  print "Not throwing exception.\n";
  $finally->invoke();

  print "Example 1 ended normally.\n";
}

function example2()
{
  $finally = new Finally("example_finally");
  print "Throwing exception!\n";
  throw new Exception("Something exceptional happened!");
  $finally->invoke();

  print "Example 2 ended normally.\n";
}


// Test harness

print "Example 1...\n";
try
{
  example1();
}
catch (Exception $e)
{
  print "Example 1 threw an exception!\n";
}

print "\nExample 2...\n";
try
{
  example2();
}
catch (Exception $e)
{
  print "Example 2 threw an exception!\n";
}


// Implementation of the Finally class

class Finally
{
  private $_callback = NULL;
  private $_args = array();

  function __construct($callback, array $args = array())
  {
    if (!is_callable($callback))
    {
      throw new Exception("Callback was not callable!");
    }

    $this->_callback = $callback;
    $this->_args = $args;
  }

  public function invoke()
  {
    if ($this->_callback)
    {
      call_user_func_array($this->_callback, $args);
      $this->_callback = NULL;
      $this->_args = array();
    }
  }

  function __destruct()
  {
    $this->invoke();
  }
}
 [2011-12-05 17:55 UTC] php dot net at kenman dot net
+1

From Zeev, in the 2000 discussion:

> try..finally doesn't make much sense in the context of PHP [...] Nobody has ever 
asked for this in the past either.

Those days are long past, please take this bug report's comments as a sign that 
this *does* now make sense for PHP.
 [2011-12-06 05:50 UTC] ben at last dot fm
"finally" would be a majorly beneficial addition to the language. It's something 
we yearn for here at last.fm.
 [2011-12-08 17:40 UTC] antoninweb at gmail dot com
I don't understand how this is not included when PHP supports try...catch. It just 
doesn't makes sense and it's annoying because you have to find ways around it 
contantly.
 [2012-01-02 12:02 UTC] frederic dot hardy at mageekbox dot net
I'm not sure that this place is the right place to discuss about that.
Since the last year, PHP has a process to discuss technical point, aka RFC 
(https://wiki.php.net/rfc).
So, if "finally" must be included in PHP, just write the relative RFC and discuss 
it on internals.
Sure that time has changed, because PHP's users are more power now than in the 
past !
 [2012-04-03 13:08 UTC] andrew dot feller at gmail dot com
The demand for "finally" is a symptom of PHP not officially and explicitly addressing supported solutions to managing resources.  I cannot find anything within PHP documentation to address this:

http://www.php.net/manual/en/language.oop5.decon.php
http://www.php.net/manual/en/faq.misc.php

So I recommend to move beyond inclusion of finalizers and start with educating constituents because there is an opportunity to resolve this and hopefully improve quality of work done by developers
 [2012-04-11 08:34 UTC] ravilov at gmail dot com
My two cents...

Here's an example of emulating "finally" in PHP without needing to duplicate code.


$_ex = null;
AllocateSomeResource();
try {
    DoSomeProcessing();
} catch (Exception $ex) {
    $_ex = $ex;
}
DeallocateSomeResource();
if ($_ex != null) {
    throw $_ex;
}


That said, I completely agree any current workaround/emulation/"solution" is nothing but cumbersome and bug-prone, and that we shouldn't have to come up with such creative ways to overcome what seems like a language design flaw. PHP is a tool, it is supposed to work *with* us, not *against* us.
 [2012-04-11 21:21 UTC] gudjonj at gmail dot com
+1 for finally in PHP
 [2012-04-12 15:42 UTC] matthias at die-legendaeren dot de
"Just going to say 'Me too!'? Don't clutter the database with that please !"

But this is the right place for a "me too": to prove that a statement from 12 
years ago was shortsighted and in a "works for me" way, developers (as customers) 
who disagree have to group behind their request.
 [2012-04-19 20:00 UTC] simon at stienen dot name
RAII is an elegant solution for tidying up scopes reliably.
It is also possible in PHP to do RAII without writing one class per resource type:

<?php

class ScopeGuard {
    private $callback;

    function __construct($callback) {
        $this->callback = $callback;
    }

    function __destruct() {
        if (is_callable($this->callback)) {
            call_user_func($this->callback);
        }
    }
}

function do_something() {
    mysql_query("LOCK TABLES mytable WRITE");
    $guard = new ScopeGuard(function() {
        mysql_query("UNLOCK TABLES");
    });

    try {
        // ... do lots of queries here
    }
}

?>

$guard will be destructed when leaving the do_something - either by throwing an exception or by exiting the function normally.

HOWEVER: RAII in C++ (which neither employs nor needs a finally keyword) is more subtle - or rather: Scopes are. In PHP you can define a variable within a loop or a conditional block - and use it afterwards. In C++ you can't. A variable defined inside a certain block will be destroyed once the block is left. Consider the following example:

<?php

function do_something() {
    if (foo) {
        mysql_query("LOCK TABLES mytable WRITE");
        $guard = new ScopeGuard(function() {
            mysql_query("UNLOCK TABLES");
        });

        try {
            // ... do lots of queries here
        }

        // *1*
    }

    do_something_else();

    // *2*
}

?>

In C++, this would work as expected of a "finally" replacement and unlock the tables at *1*, when the if scope closes. In PHP however, $guard will only be destroyed when leaving the function at *2*. This can be fixed by manually adding an unset($guard) at *1*, but this is inelegant and error prone.

So, while I have never needed finally, I think the way PHP works and is used absolutely validates its introduction as a useful addition to the language. The alternative would be to introduce C/++ style closed scopes, but those would most likely not only break a lot of existing code, but the coders as well, as they do not even remotely fit into the way PHP is written.
 [2012-04-25 20:32 UTC] toplegocreator at hotmail dot com
"Though this is still possible (however much more to type) it is wrong design. Since obviously you are using the exceptions as control flow."

If exceptions should never be propagated up the stack to a block of code that knows how to deal with them, why are exceptions there in the first place? Exceptions ARE flow control. That's their reason for existing. If they shouldn't be used that way, they shouldn't be included in the language.

Let me elaborate. An exception should occur any time when the current block cannot successfully continue execution in the current state and has no direct means (or shouldn't have any direct means because of good separation of concerns) of informing the client of the problem. A finally clause, while not strictly needed if code repetition is acceptable (and it isn't in my book), is appropriate for ensuring that resources (like database connections, open files, a printer, whatever) are released when fatal errors occur. Trying to deal with the error as some kind of returned result all the way up the stack will just make your code more difficult to read and maintain; an error should go all the way up the stack until a piece of code that's responsible for output can determine how to inform the client. That's how exceptions are supposed to be used, and a finally clause makes it possible to properly and (fairly) reliably release resources, which is also a best practice.
 [2012-05-29 21:36 UTC] kavi at postpro dot net
Since every other kitchen sink on the planet has been thrown into PHP, why not 
also the refrigerator which we all expect to be here?  Come on.  At least give a 
good reason.

Quoting topaz:

"Ugly workaround hack time!

(This is not a substitute for a real language feature!)"


...yeah, you're actually describing the *entire language* there. :|
 [2012-06-05 11:19 UTC] sgnezdov at fastmail dot fm
Finally is absolutely necessary for proper management of disposable resources.

There is no easy to read workaround for

try { 
 causeException();
} finally {
 releaseResource();
}

others pointed out that solving this issue kills re-throw, which is equally 
important.
 [2012-06-07 09:16 UTC] jl235 at kent dot ac dot uk
Most of the exceptions people come across in their PHP code tends to be for either File IO, or database access. Both of these need a finally to ensure the handle/connection/whatever gets closed, or dealt with in some other way. Using try/catch is already a lot more cumbersome then a world without Exceptions, but without finally, it adds a lot duplication and state management.

For example in my own code I do something along the lines of ...

--------------------------------------------------------

$time = microtime( true );
$sql = generateSQLQuery();
$conn = openDBConnection();
$ex = null;

try {
    $result = runSQLQuery( $conn, $sql );
} catch ( Exception $ex ) { /* do nothing */ }

closeDBConnection( $conn );
logSQLQuery( $sql, microtime(true) - $time );

if ( $ex !== null ) {
    throw $ex;
}

--------------------------------------------------------

... which could just be ...

--------------------------------------------------------

$time = microtime( true );
$sql  = generateSQLQuery();
$conn = openDBConnection();

try {
    $result = runSQLQuery( $conn, $sql );
} finally {
    closeDBConnection( $conn );
    logSQLQuery( $sql, microtime(true) - $time );
}

--------------------------------------------------------

Simpler to write, easier to read, harder to get wrong, and more elegant.

Please re-open this.
 [2012-07-05 20:17 UTC] angelo at camargo dot ws
++ for finally in PHP
 [2012-07-18 23:13 UTC] pieceofchum at yahoo dot com
Hello I am a Java developer and would like to move over to PHP for my current personal projects. The use of finally in Java is extremely powerful as it ensures that a unit of work that uses any resources that need to be managed are guaranteed to be handled before leaving the method even whent here is a catch clause. This has nothing to do with control flow and exception handling it has everything to do with contract based blocks of code in fact finally is a totally unique construct which greatly simplifies algorithms where one needs a guarantee of certain code running (usually to handle external resources) no matter what happens outside of course of an error (error defined as something that breaks the interpreter/compiler/environmen). It is not a mistake of design but a vast improvement in code clarity and application of the DRY principle which is correct programming and has nothing at all to do with improper control flow. It is not a mistake that it is in some form in Python, Ruby, Java etc... Please please recondsider adding this extremely important construct to PHP. 

Thanks for your consideration in this matter
 [2012-07-24 10:59 UTC] laruence@php.net
I will try to make a implemention.
 [2012-07-24 10:59 UTC] laruence@php.net
-Status: Closed +Status: Re-Opened -Package: Feature/Change Request +Package: *General Issues -Assigned To: +Assigned To: laruence
 [2012-07-25 23:44 UTC] pravdin at vl dot ru
We are writing large web application on PHP using the OOP and programming 
patterns. Exceptions are not only error reporting mechanism but also very 
important program flow mechanism. So, try...finally is commonly needed. Please add 
this feature. I know, PHP is not OOP, but I think there is no reason to limit 
developers needs, especially when this needs are not for just a few single 
developers.
 [2012-07-26 02:10 UTC] laruence@php.net
RFC complete, https://wiki.php.net/rfc/finally
 [2012-08-03 04:38 UTC] ceefour at gauldong dot net
Finally! :-)

Thanks a lot
 [2012-08-03 04:47 UTC] ceefour at gauldong dot net
This is awesome !

My next suggestion would be automatic resource management.

e.g. in Scala :

import resource._
val first_ten_bytes = managed(new FileInputStream("test.txt")) map { 
  input =>
     val buffer = new Array[Byte](10)
     input.read(buffer)
     buffer
}

or in Java 7 :

static String readFirstLineFromFile(String path) throws IOException {
    try (BufferedReader br =
                   new BufferedReader(new FileReader(path))) {
        return br.readLine();
    }
}

But "finally" as it stands already rocks!!! Hopefully we can see it in PHP sooner than later..... We've been waiting for a little bit too long (7 years) ;-)
 [2012-08-13 13:49 UTC] laruence@php.net
-Status: Re-Opened +Status: Closed
 [2012-08-13 13:49 UTC] laruence@php.net
This bug has been fixed in SVN.

Snapshots of the sources are packaged every three hours; this change
will be in the next snapshot. You can grab the snapshot at
http://snaps.php.net/.

 For Windows:

http://windows.php.net/snapshots/
 
Thank you for the report, and for helping us make PHP better.


 [2012-09-01 01:34 UTC] andrew dot feller at gmail dot com
It has been nearly 3 weeks but this fix cannot be found in PHP trunk at http://snaps.php.net/  Was there a build this was slated to be included within?
 [2012-09-01 07:00 UTC] laruence@php.net
that trunk is 5.4-branch-master

please fetch it by git clone:  http://git.php.net/?p=php-src.git;a=summary
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu Nov 21 09:01:32 2024 UTC