PHP Tutorial PHP Advanced PHP References

PHP Exception - getMessage() Method



The PHP Exception::getMessage() method is used to get the Exception message.

Syntax

final public Exception::getMessage()

Parameters

No parameter is required.

Return Value

Returns the Exception message as a string.

Example: Exception::getMessage() example

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

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

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

The output of the above code will be:

Division by zero is invalid.

❮ PHP - Exceptions