PHP reports notices, warnings, and errors. Modern code throws exceptions for exceptional paths and logs details instead of displaying them to users in production.
Exception basics
try {
if ($id < 1) {
throw new InvalidArgumentException('Invalid id');
}
} catch (InvalidArgumentException $e) {
http_response_code(400);
echo json_encode(['error' => $e->getMessage()]);
}
Custom exceptions
Extend Exception or SPL types (RuntimeException, LogicException) for domain errors—catch specific types, not everything blindly.
Production vs development
- Dev:
display_errors=On, verbose stack traces - Prod:
display_errors=Off, log to file/monitoring, generic user message
Important interview questions and answers
- Q: Error vs exception in PHP?
A: Traditional errors are procedural; exceptions are OOP control flow—many errors convert toErrorexceptions in PHP 7+ for fatals in some cases. - Q: finally block?
A: Runs whether or not catch matched—use for cleanup (close handles).
Self-check
- Should production show stack traces to visitors?
- When throw vs return an error array?
Challenge
Validate and throw
- Write a function that throws if email is invalid.
- Call it in try/catch and echo the message.
Done when: invalid email produces a caught exception message in output.