PHP Tutorial PHP Advanced PHP References

PHP Exception - getCode() Method



The PHP Exception::getCode() method is used to get the Exception code.

Syntax

final public Exception::getCode()

Parameters

No parameter is required.

Return Value

Returns the exception code as int in Exception but possibly as other type in Exception descendants.

Example: Exception::getCode() example

The example below shows the usage of Exception::getCode() 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) {
  $code = $e->getCode();
  echo "The exception code is: $code";
}
?>

The output of the above code will be:

The exception code is: 25

❮ PHP - Exceptions