I'm writing a PHP library and I have a concern. I have something similar to the following in my interfaces:
<?php
/**
* My interface
*
* ...
*/
interface MyInterface
{
/**
* This method does foo.
*
* @throws \RuntimeException If foo can't be done.
*/
public function fooAndBar();
}
?>
Now, the @throws
entry isn't perfectly right, since an interface doesn't actually do anything, and is used purely to abstract implementation details. However, I've always used it because all my implementations of the interface thrown the exception when something goes wrong.
But another developer might write an implementation that can't fail (so it can't throw an exception), or he/she might want to use another exception class.
In this situation, how should I document @throws
in interface declarations? Should it even be documented?
Yes, the abstract methods of an interface can throw an exception.
"Use the Javadoc @throws tag to document each unchecked exception that a method can throw, but do not use the throws keyword to include unchecked exceptions in the method declaration. "
Interfaces define contracts. Whether an implementing class throws an Exception is an implementation detail in PHP because there is no throws
keyword in the method signature (like in Java). Adding a @throws
annotation cannot enforce the contract technically, but it can indicate convention (same for return values btw). Whether that is good enough is up to you to decide.
On a sidenote, if a developer comes up with an implementation that doesn't throw you dont have a problem because you will have to add a try/catch block anyway for those implementations that do throw (by convention). It would be a problem if an implementation starts throwing a different Exception than indicated in the DocBlock because then it wouldn't be catched.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With