In this tutorial, you shall learn how to read or get the exception message in PHP using getMessage() method, with the help of example programs.

PHP – Get Exception Message

In PHP, we can access the exception message from the exception object by calling getMessage() method on the exception object.

Syntax

If e is the exception object, then the syntax to get the exception message from this object is

e->getMessage()
ADVERTISEMENT

Example

In the following program, we have a division operation where the denominator is zero. We enclose this code in a try-catch statement.

The code in try-block throws DivisionByZeroError, we catch the same in the catch-block, and echo the message present in the exception object.

PHP Program

<?php
  try {
    $a = 10;
    $b = 0;
    $c = $a / $b;
    echo $c;
  } catch (DivisionByZeroError $e) {
    echo $e->getMessage();
  }
?>

Output

PHP - Print Exception Message

References

Conclusion

In this PHP Tutorial, we learned how to get the exception message from the exception object.