PHP Tutorial PHP Advanced PHP References

PHP Exception __toString() Method



The PHP Exception::__toString() method is used to return the string representation of the exception.

Syntax

public Exception::__toString()

Parameters

No parameter is required.

Return Value

Returns the string representation of the exception.

Example: Exception::__toString() example

The example below shows the usage of Exception::__toString() method.

<?php
function divide($dividend, $divisor) {
  if($divisor == 0) {
    throw new Exception("Division by zero is invalid.", 25);
  }
  return $dividend / $divisor;
}

try {
  echo divide(25, 0);
} catch(Exception $e) {
  echo $e;
}
?>

The output of the above code will be similar to:

Exception: Division by zero is invalid. in Main.php:4
Stack trace:
#0 Main.php(10): divide()
#1 {main}

❮ PHP - Exceptions