Can I declare that a php function throws an exception?

shay picture shay · Jul 24, 2010 · Viewed 34.4k times · Source

Can I declare a function in php that throws an exception? For example:

public function read($b, $off, $len) throws IOException 

Answer

Gilad picture Gilad · Apr 28, 2013

You can use @throws in the PHPDoc comment, and the IDE will recognize this function as throwing an exception, when viewing the doc, however unlike Java it will not force you to implement the Try{}catch block. Maybe future versions of the IDE (I am using InteliJ 11) will mark those places where try{}catch is expected, that same as it already do with the JavaScript types marked by doc (e.g. String}) when recognizing inconsistency.

In short, using Doclet like when codding with scripting languages (PHP, JavaScript..), is turn to be complementary tool for safer programming in the case of non type-safe and non compiled languages.

like this:

enter code here
/**
 * Handle 'get' operations
 * @abstract
 * @param int $status reference for setting the response status
 * @param String $body reference for setting the response data
 * @return mixed
 * @throws Exception if operation fail
 */
function get(&$status, &$body) {
}

enter image description here