Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to document @throws in interface documentation

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 @throwsentry 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?

like image 347
Alessandro Desantis Avatar asked May 27 '12 20:05

Alessandro Desantis


People also ask

Can we throw exception in interface method?

Yes, the abstract methods of an interface can throw an exception.

How to document exceptions in Java?

"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. "


1 Answers

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.

like image 99
Gordon Avatar answered Sep 17 '22 12:09

Gordon