Exception Best Practices
Use exceptions for exceptional conditions, not normal flow control. Be specific with exception types, log with context, and never swallow exceptions silently.
Use exceptions for exceptional conditions, not normal flow control. Be specific with exception types, log with context, and never swallow exceptions silently.
<?php
// BAD: using exceptions for control flow
try {
$user = findUser($id); // throws if not found
} catch (NotFoundException $e) {
$user = createDefaultUser(); // Not exceptional — just use null return
}
// GOOD: return null for "not found", exception for actual errors
$user = findUser($id) ?? createDefaultUser();
// BAD: empty catch (silent failure)
try { doSomething(); } catch (Exception $e) {} // Bug swallower!
// GOOD: always log or rethrow
try {
doSomething();
} catch (Exception $e) {
$logger->error("Failed: " . $e->getMessage());
throw $e;
}
An empty catch block is one of the most dangerous things in PHP — always at minimum log the exception.