<?php
class CustomException extends Exception
{
// Redefine the constructor so message isn't optional
public function __construct($message, $code = 0, ?Throwable $previous = null) {
// some code
// Ensure everything is assigned properly
parent::__construct($message, $code, $previous);
}
// Custom string representation of object
public function __toString() {
return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
}
public function customFunction() {
echo "A custom function for this type of exception\n";
}
}
try {
throw new CustomException("Something happened", 5);
} catch (CustomException $e) {
echo "Caught custom exception\n", $e;
$e->customFunction();
}
The above example will output:
Caught custom exception
CustomException: [5]: Something happened
A custom function for this type of exception