Exception and Error handling

suggest change

try/catch

try..catch blocks can be used to control the flow of a program where Exceptions may be thrown. They can be caught and handled gracefully rather than letting PHP stop when one is encountered:

try {
    // Do a bunch of things...
    throw new Exception('My test exception!');
} catch (Exception $ex) {
    // Your logic failed. What do you want to do about that? Log it:
    file_put_contents('my_error_log.txt', $ex->getMessage(), FILE_APPEND);
}

The example above catches the exception thrown in the try block and appends its message (My test exception!) to a text file.

Catching different Exception types

You can implement multiple catch statements for different types of exceptions to be handled in different ways, for example:

try {
    throw new InvalidArgumentException('Argument #1 must be an integer!');
} catch (InvalidArgumentException $ex) {
    var_dump('Invalid argument exception caught: ' . $ex->getMessage());
} catch (Exception $ex) {
    var_dump('Standard exception caught: ' . $ex->getMessage());
}

In the above example the first catch will be used since it matches first in the order of execution. If you swapped the order of the catch statements around, the Exception catcher would execute first.

Similarly, if you were to throw an UnexpectedValueException instead you would see the second handler for a standard Exception being used.

finally

If you need something to be done after either a try or a catch has finished running, you can use a finally statement:

try {
    throw new Exception('Hello world');
} catch (Exception $e) {
    echo 'Uh oh! ' . $e->getMessage();
} finally {
    echo " - I'm finished now - home time!";
}

The above example would output the following:

Uh oh! Hello world - I’m finished now - home time!

throwable

PHP 7 introduced the Throwable interface. Both Error and Exception implement it. A user class cannot implement Throwable directly. Extend Exception or Error instead. catch (Exception $ex) does not catch Error.

$handler = function (\Throwable $ex) {
    $msg = "[ {$ex->getCode()} ] {$ex->getTraceAsString()}";
    mail('admin@server.com', $ex->getMessage(), $msg);
    echo myNiceErrorMessageFunction();
};
set_exception_handler($handler);

set_exception_handler() receives an uncaught Throwable. set_error_handler() receives an error number and a message, not a Throwable, so this closure cannot be registered as the error handler.

Before PHP 7, type-hint Exception. Every exception class extended it, and Error did not exist yet.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents