.. _structures-tostringthrowsexception: .. _\_\_tostring()-throws-exception: __toString() Throws Exception +++++++++++++++++++++++++++++ Magical method `__toString() `_ can't throw exceptions. In fact, `__toString() `_ may not let an `exception `_ pass. If it throw an `exception `_, but must catch it. If an underlying method throws an `exception `_, it must be caught. A fatal `error `_ is displayed, when an `exception `_ is not intercepted in the `__toString() `_ function. .. code-block:: php string = $string; } public function __toString() { // Do not throw exceptions in __toString if (!is_string($this->string)) { throw new Exception("$this->string is not a string!!"); } return $this->string; } } ?> See also __toString(). Related PHP errors ------------------- + `0 `_ Connex PHP features ------------------- + `exception `_ + `magic-method `_ Suggestions ___________ * Remove any usage of exception from __toString() magic method Specs _____ +--------------+-------------------------------------------------------------------------------------------------------------------------+ | Short name | Structures/toStringThrowsException | +--------------+-------------------------------------------------------------------------------------------------------------------------+ | Rulesets | :ref:`All `, :ref:`Analyze `, :ref:`Changed Behavior ` | +--------------+-------------------------------------------------------------------------------------------------------------------------+ | Exakat since | 0.8.4 | +--------------+-------------------------------------------------------------------------------------------------------------------------+ | PHP Version | With PHP 7.4 and older | +--------------+-------------------------------------------------------------------------------------------------------------------------+ | Severity | Major | +--------------+-------------------------------------------------------------------------------------------------------------------------+ | Time To Fix | Quick (30 mins) | +--------------+-------------------------------------------------------------------------------------------------------------------------+ | Precision | Very high | +--------------+-------------------------------------------------------------------------------------------------------------------------+ | Available in | `Entreprise Edition `_, `Exakat Cloud `_ | +--------------+-------------------------------------------------------------------------------------------------------------------------+