Exceptions and normal program flow

Exceptions should never be used as normal program flow. If removing all exception handling logic (try-catch statements) from the program, the remaining code should represent the "One True Path" -- the flow that would be executed in the absence of errors.

This requirement is equivalent to requiring that exceptions be thrown only on error conditions, and never in normal program states.

One example of a method that wrongly uses the bubble up capability of exceptions to return a result from a deep recursion:


 * Recursively search a tree for string.
 * @throws ResultException
public function search(TreeNode $node$data)
    if (
$node->data === $data) {
         throw new 
ResultException$node );
    } else {
search$node->leftChild$data );
search$node->rightChild$data );

In the example the ResultException is simply using the "eject!" qualities of exception handling to jump out of deeply nested recursion. When actually used to signify an error this is a very powerful feature, but in the example above this is simply lazy development.

Error Signaling in PHP5 PEAR packages (Previous) Exception class hierarchies (Next)
Last updated: Sat, 16 Feb 2019 — Download Documentation
Do you think that something on this page is wrong? Please file a bug report.
View this page in:
  • English

User Notes:

There are no user contributed notes for this page.