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 above example would catch the Exception thrown in the try block and log it’s 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

In PHP 7 we see the introduction of the Throwable interface, which Error as well as Exception implements. This adds a service contract level between exceptions in PHP 7, and allows you to implement the interface for your own custom exceptions:

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

Prior to PHP 7 you can simply typehint Exception since as of PHP 5 all exception classes extend it.

Feedback about page:

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


Exception handling and error reporting:
* Exception and Error handling

Table Of Contents
2 Arrays
4 Types
6 Exception handling and error reporting
10 Cookies
14 JSON
15 SOAP
17 cURL
19 XML
21 Traits
35 UTF-8
36 URLs
38 PHPDoc
41 Loops
44 Closur
72 YAML
77 Cache
78 Streams
81 PDO
82 SQLite3
83 Sockets
87 MongoDB
93 IMAP
94 Redis
95 Imagick
102 APCu
108 PSR