41. Error Handling and Reporting
Proper error handling is vital for security and maintainability. PHP errors are categorized by severity.
Types of Errors
- Notices (
E_NOTICE): Runtime issues that aren't critical (e.g., accessing an undefined variable). PHP keeps running. - Warnings (
E_WARNING): More serious runtime problems (e.g., including a missing file viainclude). PHP keeps running. - Fatal Errors (
E_ERROR): Critical problems (e.g., calling an undefined function, usingrequireon a missing file). Stops script execution immediately.
Controlling Error Reporting
The error_reporting() function controls which errors PHP displays. It is crucial to hide errors on production servers.
php
Try-Catch Blocks (Exception Handling)
For OOP and modern applications, we handle errors using throw (to raise an error/exception) and try...catch (to gracefully manage it).
php
Caught Exception: " . $e->getMessage(); // Typically you would log this error, not just echo it } finally { // This block runs regardless of success or failure echo "\nFinished attempting division."; } ?>