Create a gist now

Instantly share code, notes, and snippets.

@7php /TheBadCode
Last active Dec 28, 2015

What would you like to do?
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