note 79036 added to language.exceptions

From: Date: Wed, 07 Nov 2007 23:43:21 +0000
Subject: note 79036 added to language.exceptions
Groups: php.notes 
Request: Send a blank email to php-notes+get-132091@lists.php.net to get a copy of this message
If you are going to use multiple catches within a try-catch then do not forget the stacking order of those catches! This is important as any classes that extend the Exception class, like MyException in example 20.3, will be caught in the Exception case. This is because your newly extended class also has a class type of Exception. This baffled me for awhile as the examples here worked but mine didn't because my first catch was trying to catch Exception. Example: <?php /** * My1Exception extends Exception * My2Exception extends Exception */ /** * This will always fall in the first exception */ try { throw new My1Exception("My fail english? That's unpossible", 69); } catch (Exception $e) { print "Incorrect Exception"; } catch (My1Exception $e) { print "Correct Exception but I won't be here"; } catch (My2Exception $e) { print "Again, incorrect"; } /** * Whereas here, the catch stacking order was changed so our throw will cascade into the correct catch */ try { throw new My1Exception("My cat's breath smells like cat food", 69); } catch (My2Exception $e) { print "Incorrect Exception"; } catch (My1Exception $e) { print "Correct Exception and I WILL be printed"; } catch (Exception $e) { print "Again, incorrect"; } ?> So, ALWAYS keep the Exception catch block at the bottom, then any of the other extended exceptions that extend from Exception, then any of your other extended exceptions that extend from those extended exceptions, etc ---- Server IP: 203.16.234.90 Probable Submitter: 203.36.207.23 ---- Manual Page -- http://www.php.net/manual/en/language.exceptions.php Edit -- https://master.php.net/note/edit/79036 Del: integrated -- https://master.php.net/note/delete/79036/integrated Del: useless -- https://master.php.net/note/delete/79036/useless Del: bad code -- https://master.php.net/note/delete/79036/bad+code Del: spam -- https://master.php.net/note/delete/79036/spam Del: non-english -- https://master.php.net/note/delete/79036/non-english Del: in docs -- https://master.php.net/note/delete/79036/in+docs Del: other reasons-- https://master.php.net/note/delete/79036 Reject -- https://master.php.net/note/reject/79036 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#132091) next »