0

Consider a class like below:

class Test{
    /**
     * @throws \Exception
     * @return void
     */
    public function validateWithCondition($value): void
    {
         if (! someCondition($value)) {
             throw new \Exception("The input $value does not fulfill condition");
         }
    }
}

It's a terrible class, but the question is regarding the @throws \Exception in the docblock. Is there any use in doing so? I can understand documenting a more specific custom exception @throws ValueDoesNotFulfilCondition (extends \Exception). But in my case, a simple generic base exception with a simple message is enough. The reasons for my doubt are the following:

  • The \Exception is too generic and the calling code might end up catching something unintentional.
  • There is no way to know the error type, other than to analyse the error message.
  • The Exception is only intended to be used for logging by the application level ErrorHandler (as in the Laravel ErrorHandler class).
  • Adding @throws \Exception basically covers all the other errors as well, since they are all extending this class. So, once that is added, even the IDE doesn't care if the other custom errors are mentioned in the docblock.

I'm asking for inputs from more experienced programmers. If it can be omitted, we're on the same page. But, if it should be documented anyway... why? Can you give an example where it could come in handy?

Thanks in advance. :)

BlackPanther
  • 1,732
  • 1
  • 14
  • 19
  • 2
    I think this is worth adding. There are methods/functions that don't throw exceptions at all. Adding this at least warns the caller that there is potential for an exception to be thrown. – bassxzero Apr 13 '23 at 05:45
  • 1
    If a method has a questionable exception choice, documenting it is a sensible mitigation. Hiding unexpected behaviour under the rug is never going to help. – Álvaro González Apr 13 '23 at 06:21

0 Answers0