Skip to content

Instantly share code, notes, and snippets.

@wkhayrattee
Last active December 28, 2015 01:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wkhayrattee/206f6f12d1763b17db51 to your computer and use it in GitHub Desktop.
Save wkhayrattee/206f6f12d1763b17db51 to your computer and use it in GitHub Desktop.
Wrongly Positioning a 'Return' Statement Inside An Inner 'Finally' Block Can Be Lethal
<?php
/**
* To demonstrate the effect of a return in a finally
*
* @author Khayrattee Wasseem <wasseem@khayrattee.com>
* @link http://7php.com (blog)
* @link http://Khayrattee.com (website)
* @copyright 2007-2015 Khayrattee.com
*/
class ClassA
{
public function hey()
{
try {
echo '<br/>try from ClassA';
throw new Exception('<strong>Exception from ClassA</strong>');
} catch (Exception $error) {
echo '<br/>catch from ClassA';
throw new Exception($error->getMessage());
} finally {
echo '<br/>Finally from ClassA';
}
}
}
class ClassB
{
public static function hello()
{
$obj = new ClassA();
try {
echo '<br/>try from ClassB';
$obj->hey();
} catch(Exception $error) {
echo '<br/>catch from ClassB';
throw new Exception($error->getMessage());
} finally {
return '<br/>finally from ClassB';
}
}
}
try {
echo '<br/>try from calling file';
ClassB::hello();
} catch (Exception $error){
echo '<br/>catch from calling file with error: ' . $error->getMessage();
} finally {
echo '<br/>finally from calling file';
}
<?php
/**
* To demonstrate the effect of a return in a finally
*
* @author Khayrattee Wasseem <wasseem@khayrattee.com>
* @link http://7php.com (blog)
* @link http://Khayrattee.com (website)
* @copyright 2007-2015 Khayrattee.com
*/
class ClassA
{
public function hey()
{
try {
echo '<br/>try from ClassA';
throw new Exception('<strong>Exception from ClassA</strong>');
} catch (Exception $error) {
echo '<br/>catch from ClassA';
throw new Exception($error->getMessage());
} finally {
echo '<br/>Finally from ClassA';
}
}
}
class ClassB
{
public static function hello()
{
$obj = new ClassA();
try {
echo '<br/>try from ClassB';
$obj->hey();
} catch(Exception $error) {
echo '<br/>catch from ClassB';
throw new Exception($error->getMessage());
} finally {
//silence is golden
}
return '<br/>finally from ClassB';
}
}
try {
echo '<br/>try from calling file';
ClassB::hello();
} catch (Exception $error){
echo '<br/>catch from calling file with error: ' . $error->getMessage();
} finally {
echo '<br/>finally from calling file';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment