php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #72295 restore_exception_handler in finally block runs before global exception handler
Submitted: 2016-05-30 21:03 UTC Modified: 2016-05-30 22:12 UTC
From: james dot beninger at gmail dot com Assigned:
Status: Not a bug Package: *General Issues
PHP Version: 7.0.7 OS: All
Private report: No CVE-ID: None
 [2016-05-30 21:03 UTC] james dot beninger at gmail dot com
Description:
------------
When restore_exception_handler is called in a finally block, the *restored* exception handler handles the exception.  I would expect the exception to be fully resolved before restore_exception_handler takes effect.

The PHP documentation states "Code within the finally block will always be executed after the try and catch blocks, regardless of whether an exception has been thrown, and before normal execution resumes."

Test script:
---------------
<?php
function handler1($e) {
  echo "\nhandler1";
}

function handler2($e) {
  echo "\nhandler2";
}

set_exception_handler('handler1');

set_exception_handler('handler2');

try {
  throw new Exception(); // 'handler1' is displayed.  Expected: 'handler2'
}
finally {
  restore_exception_handler();
}


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2016-05-30 22:12 UTC] requinix@php.net
-Summary: restore_exception_handler in finally block runs before catch +Summary: restore_exception_handler in finally block runs before global exception handler -Status: Open +Status: Not a bug
 [2016-05-30 22:12 UTC] requinix@php.net
(edited the summary for clarity)

But if that were the case then restore_exception_handler() would never happen - the script will abort after the exception handler executes. (Because the exception handler is only to give you the option to do something with the uncaught exception, not to act as a sort of global catch.)

finally works similarly to scope: it runs once execution leaves the try/catch block. In your example there is no catch block so PHP begins to bubble up the exception through the call stack, and as execution leaves the try block the finally block will execute. If there was one then it would execute first and the finally second (and if the catch block threw its own exception, bubbling that up would happen third).
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Fri Apr 26 06:01:32 2024 UTC