Saturday, October 29, 2011

Difference between PHP 4 and 5 - Exceptions

PHP finally introduces exceptions! An exception is basically an error. By using an exception however, you gain more control the simple trigger_error notices we were stuck with before.

An exception is just an object. When an error occurs, you throw an exception. When an exception is thrown, the rest of the PHP code following will not be executed. When you are about to perform something "risky", surround your code with a try block. If an exception is thrown, then your following catch block is there to intercept the error and handle it accordingly. If there is no catch block, a fatal error occurs.

try {
} catch (AccessDeniedException $e) {
die('Could not write the cache, access denied.');
} catch (Exception $e) {
die('An unknown error occurred: ' . $e->getMessage());

No comments: