Documenting Exceptions

Because PHP, unlike Java, does not require you to explicitly state which Exceptions a method throws in the method signature, it is critical that Exceptions be thoroughly documented in your method headers.

Exceptions should be documented using the @throws phpdoc keyword:

<?php
/**
 * This method searches for aliens.
 *
 * @return array Array of Aliens objects.
 *
 * @throws AntennaBrokenException If the impedence readings indicate
 *                                that the antenna is broken.
 * @throws AntennaInUseException  If another process is using the
 *                                antenna already.
 */
public function findAliens($color 'green');
?>

In many cases middle layers of an application will rewrap any lower-level exceptions into more meaningful application exceptions. This also needs to be made clear:

<?php
/**
 * Load session objects into shared memory.
 *
 * @throws LoadingException Any lower-level IOException will be wrapped
 *                          and re-thrown as a LoadingException.
 */
public function loadSessionObjects();
?>

In other cases your method may simply be a conduit through which lower level exceptions can pass freely. As challenging as it may be, your method should also document which exceptions it is not catching.

<?php
/**
 * Performs a batch of database queries (atomically, not in transaction).
 *
 * @throws SQLException Low-level SQL errors will bubble up through this method.
 */
public function batchExecute();
?>
Exception class hierarchies (Previous) Exceptions as part of the API (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.