What is the error and exception handling in PHP?
sobes.tech AI
Answer from AI
Error and exception handling in PHP allows controlling program execution when encountering incorrect situations, preventing fatal failures, and providing meaningful information to the user.
Errors
Errors are issues that occur at the PHP interpreter level. They can be syntax errors, logical errors, or errors when accessing non-existent resources. Error levels are defined by constants (E_ERROR, E_WARNING, E_NOTICE, etc.) and can be configured using error_reporting and display_errors.
Custom error handler functions, registered with set_error_handler(), are used to handle errors. This function intercepts errors (except E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING), allowing registration, message output, script termination, or continuation.
<?php
// Custom error handler function
function myErrorHandler($errno, $errstr, $errfile, $errline) {
// Log the error
error_log("Error [$errno]: $errstr in file $errfile on line $errline");
// Display message to user (depending on environment)
if (ini_get('display_errors')) {
echo "An error occurred: [$errno] $errstr<br>";
echo "In file: $errfile on line: $errline<br>";
}
// Stop script execution on critical errors
if ($errno == E_USER_ERROR) {
die("Critical error. Script stopped.");
}
// Continue standard PHP error handling if the function returns false
// return false;
}
// Register the error handler
set_error_handler("myErrorHandler");
// Example error
// echo $undeclaredVar; // Will trigger E_NOTICE
Exceptions
Exceptions are objects thrown during exceptional situations. They allow structuring code and managing flow more flexibly than traditional error handling.
Exceptions are handled using try...catch...finally blocks:
try: Block of code where an exception might occur.catch: Block executed if an exception of a specified type is thrown intryor anothercatch. Multiplecatchblocks can be used for different exception types.finally: (available since PHP 5.5) Block that always executes, regardless of whether an exception was thrown and caught.
<?php
function divide($a, $b) {
if ($b === 0) {
throw new Exception("Division by zero is not possible.");
}
return $a / $b;
}
try {
echo divide(10, 2) . "<br>";
echo divide(5, 0) . "<br>"; // Exception will be generated here
echo "This code will not execute if the previous line throws an exception.";
} catch (Exception $e) {
echo "Caught exception: " . $e->getMessage() . "<br>";
// Additional info like file, line, and stack trace can be retrieved
// echo "In file: " . $e->getFile() . " on line: " . $e->getLine() . "<br>";
// echo "Stack trace:<pre>" . $e->getTraceAsString() . "</pre>";
} finally {
// This block always executes
echo "Operation completed.<br>";
}
Exception Classes
PHP provides a base class Exception, from which other built-in exception classes inherit (e.g., InvalidArgumentException, RuntimeException). Custom exception classes can be created by inheriting from Exception or its descendants for more precise error type representation.
<?php
class MyCustomException extends Exception {
// Custom properties and methods can be added
}
function processData($data) {
if (empty($data)) {
throw new MyCustomException("No data to process.");
}
// ... process data
}
try {
processData([]);
} catch (MyCustomException $e) {
echo "Caught custom exception: " . $e->getMessage() . "<br>";
} catch (Exception $e) {
echo "Caught another exception: " . $e->getMessage() . "<br>";
}
General Principles
- Do not catch errors you cannot handle. If you don't know how to respond properly, let it bubble up for another handler.
- Exceptions are better suited for expected but exceptional situations (e.g., user input error, database connection failure). Errors often indicate issues in the code or environment.
- Log errors and exceptions. This is critical for debugging and monitoring.
- Do not reveal sensitive information to users in error messages.
- Use
set_exception_handler()to handle uncaught exceptions. This prevents fatal errors and allows graceful degradation.
<?php
// Uncaught exception handler
function myExceptionHandler($exception) {
error_log("Uncaught exception: " . $exception->getMessage());
// Redirect to error page, display a general message, etc.
echo "An unexpected server error occurred. Please try again later.";
}
set_exception_handler('myExceptionHandler');
// This code will throw an exception caught by myExceptionHandler
// throw new Exception("This is an uncaught exception.");
Thus, proper use of error and exception handling mechanisms is fundamental to creating reliable and maintainable PHP applications.