PHP Tutorial
PHP Flow Control
PHP Functions
PHP String
PHP Array
PHP Date Time
PHP Object Oriented
Regular Expression
PHP Cookie & Session
PHP Error & Exception handling
MySQL in PHP
PHP File Directory
PHP Image Processing
Error handling has significantly improved in PHP 7 with the introduction of error exceptions and the Throwable interface. Prior to PHP 7, error handling was accomplished using manual error checking, error reporting levels, and custom error handlers. While these traditional methods are still used, PHP 7 introduced new classes and interfaces for more sophisticated error handling.
Here's a simple tutorial about error handling in PHP 7:
Error Exception
PHP 7 introduces several new classes for exceptions. The base exception class is \Exception
, and two new classes \Error
and \Throwable
have been introduced. \Error
is the base class for all internal PHP errors, and \Throwable
is the base interface for any object that can be thrown via a throw
statement.
Here's a simple example:
<?php try { // Generate an exception throw new Exception('This is an exception'); } catch (Exception $e) { echo $e->getMessage(); } catch (Error $e) { echo $e->getMessage(); } ?>
In the example above, we are throwing an Exception. If we replace throw new Exception('This is an exception');
with some code that generates a PHP error, the catch (Error $e)
block will be executed.
Throwable Interface
In PHP 7, all exceptions must implement the Throwable interface. This interface is implemented by the base classes \Error
and \Exception
. This means that we can modify our catch block to catch Throwable objects, and it will catch both Errors and Exceptions.
Here's an example:
<?php try { // Generate an exception throw new Exception('This is an exception'); } catch (Throwable $t) { echo $t->getMessage(); } ?>
In this example, the catch block will catch any object of a class that implements the Throwable interface, which includes both Error and Exception objects.
Error Levels
Just like in previous versions of PHP, PHP 7 has several error reporting levels. The two primary levels you will encounter are E_ERROR, which is a fatal run-time error that can't be recovered from and halts the script execution, and E_WARNING, a run-time warning that does not halt script execution. You can set the error reporting level using the error_reporting()
function.
<?php // Report all errors except E_NOTICE error_reporting(E_ALL ^ E_NOTICE); ?>
Conclusion
Error handling in PHP 7 can be as simple or as complex as you need it to be. The new classes and interfaces make it easier to catch both errors and exceptions in one block of code. However, the traditional methods of error handling are still valid and used widely. Use the method that best fits your needs and the needs of your application.
Always remember to develop your application in an environment with strict error reporting and display errors turned on. This will help you catch and fix errors before they become a problem in your production environment.
Exception handling in PHP 7:
PHP 7 introduced improved exception handling with the introduction of the Throwable
interface. Here's an example:
<?php try { // Code that may throw an exception throw new Exception('This is a test exception'); } catch (Exception $e) { // Handle the exception echo 'Caught exception: ', $e->getMessage(), "\n"; }
Handling fatal errors in PHP 7:
Fatal errors can be handled using the register_shutdown_function()
function. Example:
<?php register_shutdown_function(function () { $error = error_get_last(); if ($error !== null && in_array($error['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING])) { echo "Fatal Error: [{$error['type']}] {$error['message']} in {$error['file']} on line {$error['line']}\n"; } }); // Trigger a fatal error undefinedFunction();
PHP 7 try-catch blocks for error handling:
Use try-catch
blocks for structured exception handling:
<?php try { // Code that may throw an exception throw new InvalidArgumentException('Invalid argument exception'); } catch (InvalidArgumentException $e) { // Handle specific exception echo 'Caught exception: ', $e->getMessage(), "\n"; } catch (Exception $e) { // Handle general exception echo 'Caught exception: ', $e->getMessage(), "\n"; }
Error suppression with the @ symbol in PHP 7:
The @
symbol can be used to suppress errors and warnings. Example:
<?php $result = @file_get_contents('nonexistent_file.txt'); if ($result === false) { echo 'Error reading file.'; }
PHP 7 error_reporting()
function for error control:
Use the error_reporting()
function to control which errors are reported. Example:
<?php // Report all errors error_reporting(E_ALL); // Code that may produce errors
PHP 7 error_log()
function for logging errors:
Use the error_log()
function to log errors to the server's error log or a custom log file:
<?php $message = 'An error occurred.'; error_log($message, 3, 'error.log'); // 3 represents the option to append to the log file
PHP 7 error handling with custom error handlers:
Implement custom error handlers using the set_error_handler()
function. Example:
<?php function customErrorHandler($errno, $errstr, $errfile, $errline) { echo "Custom Error: [$errno] $errstr in $errfile on line $errline\n"; } set_error_handler("customErrorHandler"); // Trigger an error echo $undefinedVariable;