Table of Contents

Request for Comments: Supports finally keyword

Introduction

This RFC is try to introduce 'finally' support for exceptions. which is requested from FR #32100, #36779

without this feature, user have to write codes like following one to do cleanup while an un-handlable exception occurred:

<?php
$db = mysqli_connect();
try {
   call_some_function($db);
} catch (Exception $e) {
   mysqli_close($db);
   throw $e;
}
mysql_close($db);

introducing finally is not about save one or two lines for such situation, it's about give the user a more proper way to handle such issue.

Proposal

The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.

<?php
$db = mysqli_connect();
try {
   call_some_function($db);//the function may throw exceptions which we can not handle
} finally {
   mysqli_close($db);
}

the most confuse part is call “return in try/catch block”, in this case the finally block will still be called

<?php
  try {
    return 2;
  } finally {
    echo "this will be called\n";
  }
  //this will never be called
  echo "you can not see me";

the above script will output:

this will be called
//return int(2)

and for nesting try catch finally:

<?php
function foo ($a) {
   try {
      echo "1";
      try {
        echo "2";
        throw new Exception("ex");
      } catch (Exception $e) {
        echo "3";
      } finally {
        echo "4";
        throw new Exception("ex");
      } 
   } catch (Exception $e) {
      echo "3";
   } finally {
      echo "2";
   }
   return 1;
}
 
var_dump(foo("para"));

will output:

123432int(1)

There are also lots of edge cases could be found in the Test&Examples section blow

Patch

Tests & Examples

Vote

Should the implementation be merged into trunk?
Real name Yes No
ab (ab)  
aharvey (aharvey)  
arpad (arpad)  
bjori (bjori)  
colder (colder)  
derick (derick)  
dragoonis (dragoonis)  
felipe (felipe)  
googleguy (googleguy)  
guilhermeblanco (guilhermeblanco)  
hytest (hytest)  
indeyets (indeyets)  
ircmaxell (ircmaxell)  
irker (irker)  
joey (joey)  
jpauli (jpauli)  
kassner (kassner)  
klaussilveira (klaussilveira)  
kriscraig (kriscraig)  
laruence (laruence)  
levim (levim)  
nikic (nikic)  
pajoye (pajoye)  
rasmus (rasmus)  
sascham78 (sascham78)  
shm (shm)  
stas (stas)  
tyrael (tyrael)  
willfitch (willfitch)  
zhangzhenyu (zhangzhenyu)  
Final result: 25 5
This poll has been closed.

Changelog