note 119730 rejected from language.exceptions by cmb
| From: | cmb@php.net | Date: | Sat, 13 Aug 2016 00:49:09 +0000 |
| Subject: | note 119730 rejected from language.exceptions by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-206270@lists.php.net to get a copy of this message | ||
Note Submitter: xedin dot unknown at gmail dot com
----
Unexplicable, strange behaviour when using the default exception handler.
<?php
interface MyEx {}
class MyExA extends Exception implements MyEx {}
class MyExB extends Exception implements MyEx {}
function myExceptionHandler(Exception $e)
{
echo sprintf('Exception of type %1$s was thrown with message "%2$s"',
get_class($e), $e->getMessage()) . PHP_EOL;
if ($ie = $e->getPrevious()) {
echo sprintf('This exception also has an inner exception of type %1$s with message
"%2$s"', get_class($ie), $e->getMessage()) . PHP_EOL;
}
}
function testA1()
{
try {
call_user_func_array(function () {
throw new MyExA('Internal problem');
}, array());
} catch (MyEx $ex1) {
throw new MyExB('External problem', 0, $ex1);
}
}
function testA2()
{
set_exception_handler('myExceptionHandler');
try {
call_user_func_array(function () {
throw new MyExA('Internal problem');
}, array());
} catch (MyEx $ex1) {
throw new MyExB('External problem', 0, $ex1);
}
}
function testB1()
{
set_exception_handler('myExceptionHandler');
try {
throw new MyExA('Internal problem');
} catch (MyEx $ex1) {
throw new MyExB('External problem', 0, $ex1);
}
}
function testB2()
{
try {
throw new MyExA('Internal problem');
} catch (MyEx $ex1) {
throw new MyExB('External problem', 0, $ex1);
}
}
function test()
{
testA1();
// testA2();
// testB1();
// testB2();
}
test();
?>
The output of the above code is below:
"Fatal error: Uncaught exception 'MyExA' with message 'Internal
problem'". Note that the reported exception is the one of type
MyExA, and
with the message given to it - it's not the reported type that is wrong, but the reported
exception.
If you comment out line with testA1() and uncomment the one with testA2(),
the output is as follows:
'Exception of type MyExB was thrown with message "External problem" This exception
also has an inner exception of type MyExA with message "Internal problem"'
This means that the correct exception of type MyExB is being thrown to the top-most
scope, but PHP reports the exception of type MyExA.
The results of running testB1() VS testB2() are similar, which means that
the problem is not related to the inner exception being thrown inside a closure run by
call_user_func_array().