What the hell is an Exception, really? ★ When should I throw an Exception? ★ Is there any PHP-specific craziness I should know about? ★ Why don’t some folk like Exceptions and what are the alternatives? ★ Are there any best practices when using Exceptions? 4
between normal values and error values? ★ (AKA the Semipredicate Problem) ★ No stacktrace, no message, no context ★ Dealing with multiple function calls soon gets messy ★ Violates Command Query Separation 7
which code can pass along errors or exceptional events to the code that called it” Code Complete 2, Steve McConnell 9 What the hell is an Exception, really? an alternative channel
from Zend_Rest_Client public function setUri($uri) { if ($uri instanceof Zend_Uri_Http) { $this->_uri = $uri; } else { $this->_uri = Zend_Uri::factory($uri); } return $this; } 14 When should I throw an Exception?
from Zend_Rest_Client private function _prepareRest($path) { // Get the URI object and configure it if (!$this->_uri instanceof Zend_Uri_Http) { throw new Zend_Rest_Client_Exception('URI object must be set before performing call'); } } 15 When should I throw an Exception?
instanceof Zend_Uri_Http) { $this->_uri = $uri; } elseif ( ! is_numeric($uri)) { $this->_uri = Zend_Uri::factory($uri); } else { throw new Zend_Rest_Client_Exception('URI must be instance of Zend_Uri_Http or a String'); } } Are we losing Context? Are we passing on an error down the call chain? 16 When should I throw an Exception? // Snippet from Zend_Rest_Client public function setUri($uri) { if ($uri instanceof Zend_Uri_Http) { $this->_uri = $uri; } else { $this->_uri = Zend_Uri::factory($uri); } }
this code still run if I remove all the exception handlers?” If the answer is “no” then you maybe exceptions are being used in non- exceptional circumstances” The Pragmatic Programmer try { $this->getUser(); } catch (UserNotLoggedInException $e) { $this->redirect('/login'); } 17 When should I throw an Exception?
★ Us the programmer ★ The newer PHP5 components (PDO, DateTime, Sqlite, etc) ★ Errors are ‘triggered’ by the older procedural PHP core functions ★ Return values are returns from core functions when a non-exceptional event occurs 27 Is there any PHP-specific craziness I need to know about?
allow the programmer to interact with Errors set_error_handler('newErrorHandler'); restore_error_handler(); 28 Is there any PHP-specific craziness I need to know about?
} protected function _parseIniFile($filename) { set_error_handler(array($this, '_loadFileErrorHandler')); restore_error_handler(); if ($this->_errorStr !== null) { throw new Zend_Config_Exception($this->_errorStr); } } 29 Is there any PHP-specific craziness I need to know about? $iniArray = parse_ini_file($filename, true); How Zend Framework deals with Errors
on the internet about how to connect to a database you simply must use this. Please stop. ★ No context other than the string it was passed ★ Terminates immediately ★ Better to use Exceptions 30 Is there any PHP-specific craziness I need to know about?
don't know what to do about it @$zombie->reanimate(); ★ The Suppression Operator sets ERROR_REPORTING to 0 executes the given function then reverts ERROR_REPORTING to its previous setting. ★ If a fatal Error occurs during the suppressed function, the program will terminate with no indication why. 33 Is there any PHP-specific craziness I need to know about?
LogicException BadFunctionCallException BadMethodCallException DomainException InvalidArgumentException LengthException OutOfRangeException RuntimeException OutOfBoundsException OverflowException RangeException UnderflowException UnexpectedValueException 34 Is there any PHP-specific craziness I need to know about?
complexity = more bugs "An Exception represents an immediate nonlocal transfer of control - it's a kind of cascading goto" The Pragmatic Programmer 37 Why not Exceptions and what are the alternatives?
then return 'good enough' data ★ Closest legal value ★ The next/previous piece of valid data ★ Neutral value 41 Why not Exceptions and what are the alternatives?
type='text' value='<?php echo $zombie->getName(); ?>' /> <p>Infection Date:</p> <input type='text' value='<?php echo $zombie-> getInfectionDate(); ?>' /> 42 Why not Exceptions and what are the alternatives?
curl_setopt( $ch, CURLOPT_URL, "http://en.wikipedia.org/wiki/Zombie" ); $result = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if ($httpCode == 418) { throw new TeapotException(); } 44 Why not Exceptions and what are the alternatives?
to define what is correct circumstances ★ pre-conditions: must be true for routine to work correctly ★ post-conditions: will be true after routine has worked correctly 46 Why not Exceptions and what are the alternatives?
since PHP4 class Human{} class Zombie{} function eliminate($target) { assert('$target instanceof Zombie'); } eliminate(new Human); ★ But... it uses errors. Yuck. // PHP Warning: assert(): Assertion "$target instanceof Zombie" failed in zombie.php on line 6 47 Why not Exceptions and what are the alternatives?
★ Why is it throwing an Exception for an unexceptional circumstance? Or a problem in the catch(): ★ Why doesn’t it handle the Exception? 50 Are there best practices when using Exceptions?
catch an Exception based on class ★ Not solely reliant on the Exception's message to provide information ★ Avoid namespace clashes if two libraries both throw \exception() 51 Are there best practices when using Exceptions?
// rotate 90 degrees, retry } catch (MotionLib_ShoppingMallDoorBarricadedException $e) { // groan, press up against glass and wait } 53 Are there best practices when using Exceptions?
expose implementation details through Exceptions try { $human->getBrains(); } catch (FileNotFoundException $e) { error_log($e->getMessage()); } 54 Are there best practices when using Exceptions?
- Steve McConnell The Pragmatic Programmer - Hunt & Thomas The Practice of Programming - Kernighan & Pike Exceptional PHP : Introduction To Exceptions - Brandon Savage How to use SPL Exception Classes - Jani Hartikainen Exceptions - Joel Spolsky Should a failed function return a value or throw an exception? - Jani Hartikainen Error codes or Exceptions? Why is Reliable Software so Hard? - Damien Katz Exception Best Practices in PHP 5.3 - Ralph Schindler 57
- Stuart Herbert Design by Contract in PHP with Assertions - Luke Maciak Return False with prudence - David Winterbottom What are the principles guiding your exception handling policy? - Stackoverflow Effiel Presentations 58