Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

Exception

The base class of exceptions.

Syntax

new Exception(string $message = "", int $code = 0, ?Throwable $previous = null)

Parameters

ParameterTypeDescription
$messagestringOptional. The error message.
$codeintOptional. A numeric error code.
$previous?ThrowableOptional. 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 42

A 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 declined

Notes

PHP's own errors — TypeError, DivisionByZeroError — extend Error, not Exception. To catch both, catch Throwable.

See also

Related recipes

In the tutorial

  • Exceptions — Exceptions in PHP — throw, try, catch and finally, custom exception classes and built-in errors.

Thanks for reading!

Donate to the site — we work hard for you.