Advanced PHP · Lesson 2 of 10
Error Handling
Handle expected failures explicitly and keep diagnostic details private.
Lesson
Errors and exceptions indicate different kinds of failure, but both need a deliberate policy. Handle expected problems near the operation that can recover from them; log enough context for maintainers without exposing secrets or stack traces to users. Configure detailed errors off in production.
An error response should remain useful without disclosing internal implementation details.
Further guidance
Make failure behavior explicit at system boundaries: validate decoded data, handle expected exceptions, and log diagnostics without exposing them to visitors. Keep dependencies locked and current, use a consistent namespace/autoloading scheme, and test error paths as well as successful responses.
Practice task: Create a fresh example for Error Handling. Predict the result before running it, then change one input and explain why the result changes. Test a normal case and one boundary or invalid case where it applies. Compare your output with the example and note one rule you would use in a real project.
Code examples
Error Handling
PHP
try {
$contents = file_get_contents($path);
if ($contents === false) {
throw new RuntimeException('Unable to read file');
}
} catch (RuntimeException $exception) {
error_log($exception->getMessage());
echo 'The requested file is unavailable.';
}
Expected output
A generic message if reading fails
Key points
- Handle expected failures explicitly and keep diagnostic details private.
- Handle expected errors explicitly without exposing diagnostics.
- Keep dependency and runtime configuration reproducible.
Your learning progress
Finish this lesson
Optional practice
PHP playground
This site does not execute learner-provided PHP code. Connect a secured PHP sandbox service before enabling code execution.
Execution is disabled. No code is sent to a server.