Exception
The base class of exceptions.
Syntax
new Exception(string $message = "", int $code = 0, ?Throwable $previous = null)Parameters
| Parameter | Type | Description |
|---|---|---|
| $message | string | Optional. The error message. |
| $code | int | Optional. A numeric error code. |
| $previous | ?Throwable | Optional. The exception that caused this one. |
Return value
ExceptionAn object with the `getMessage()`, `getCode()`, `getFile()` and `getLine()` methods.
Examples
Throwing and catching:
<?php
try {
throw new Exception('Something went wrong', 42);
} catch (Exception $error) {
echo $error->getMessage(), ' ', $error->getCode();
}Output:
Something went wrong 42A custom exception class:
<?php
class PaymentFailed extends Exception {}
try {
throw new PaymentFailed('Card declined');
} catch (PaymentFailed $error) {
echo get_class($error), ': ', $error->getMessage();
}Output:
PaymentFailed: Card declinedNotes
PHP's own errors — TypeError, DivisionByZeroError — extend Error, not Exception. To catch both, catch Throwable.
See also
- InvalidArgumentException — The exception for an invalid function argument.
- PDO — A database connection.
Related recipes
In the tutorial
- Exceptions — Exceptions in PHP — throw, try, catch and finally, custom exception classes and built-in errors.