
PHP is a widely-used scripting language in web applications. Like any software, applications written in PHP may also encounter errors. In this article, I’ll explain error handling and exception mechanisms in PHP in detail.
1. Types of Errors in PHP
In PHP, errors are generally categorized into three types:
- Notice: Minor warnings that do not stop code execution. E.g., using an undefined variable.
- Warning: More serious, but code continues to execute. E.g., including a non-existent file.
- Fatal Error: Critical errors that stop code execution. E.g., calling an undefined function.
2. Using error_reporting()
for Error Management
To control which levels of errors are displayed in PHP:
error_reporting(E_ALL); // Show all errors
echo $undefinedVariable; // Will throw a notice
To hide specific error types:
error_reporting(E_ERROR | E_WARNING); // Show only errors and warnings
3. Custom Error Handling with set_error_handler()
You can define your own error handler function in PHP using set_error_handler()
:
function handleError($errno, $errstr, $errfile, $errline) {
echo "Error: [$errno] $errstr - File: $errfile Line: $errline\n";
return true;
}
set_error_handler('handleError');
This allows you to format and handle error output in a custom way.
4. Using Exceptions in PHP
PHP 5 and later supports exceptions using try-catch
blocks.
4.1. Basic Exception Usage
try {
throw new Exception('An error occurred!');
} catch (Exception $e) {
echo 'Error Message: ' . $e->getMessage();
}
4.2. Defining a Custom Exception Class
class MyException extends Exception {
public function errorMessage() {
return 'Custom Error: ' . $this->getMessage();
}
}
try {
throw new MyException('A custom error occurred!');
} catch (MyException $e) {
echo $e->errorMessage();
}
5. Resource Handling with finally
Block
Since PHP 5.5, the finally
block can be used to run code regardless of whether an exception was thrown:
try {
echo "Code is running...\n";
throw new Exception("Something went wrong");
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
} finally {
echo "This code will always run.";
}
6. Logging Errors with error_log()
Instead of printing errors to the screen, you can log them to a file:
error_log('This is an error message.', 3, 'error_log.txt');
This command writes the error message to the error_log.txt
file.
Proper error handling in PHP is essential for developing secure and stable applications. By using error_reporting()
, set_error_handler()
, try-catch
blocks, and error_log()
, you can build more robust code. An effective error management strategy improves the experience for both developers and users.
Related Articles
