No finally in PHP Exceptions

Posted by Tres Sat, 19 Apr 2008 14:12:00 GMT

PHP’s implementation of Exceptions works just like you’d expect it to, except for the missing finally statement.

In Java, we could do something like this:

        try {
            //create a new widget
            Widget widget = new Widget();
            //here's where we lock the widget before we take action
            widget.lock();
            widget.doStuf();
        } catch( TimeoutException e ) {
            widget.fixTimeoutException();
        } catch( ConnectionException e ) {
            widget.resetConnection();
        } catch( PermissionException e ) {
            widget.exit();
        } catch( FantasticException e ) {
            widget.goBallistic();
        } finally {
            //make sure that we're unlocking the widget since we put a lock on it before
            widget.unlock();
        } 

But when describing the same thing in PHP, we’ve got to do it like this because there’s no finally available:

try{
    //create a new widget
    $widget = new Widget();
    //here's where we lock the widget before we take action
    $widget->lock();
    $widget->doStuff();
} catch( TimeoutException $e ) {
    $widget->fixTimeoutException();
    //make sure that we're unlocking the widget since we put a lock on it before
    $widget->unlock();
} catch( ConnectionException $e ) {
    $widget->resetConnection();
    //make sure that we're unlocking the widget since we put a lock on it before
    $widget->unlock();
} catch( PermissionException $e ) {
    $widget->exit();
    //make sure that we're unlocking the widget since we put a lock on it before
    $widget->unlock();
} catch( FantasticException $e ) {
    $widget->goBallistic();
    //make sure that we're unlocking the widget since we put a lock on it before
    $widget->unlock();
}

It’s great to have exceptions in PHP, don’t get me wrong, it just took me by surprise that the implementation wasn’t complete.

Posted in , ,  | Tags , , ,