SyntaxStudy
Sign Up
PHP Exception Best Practices
PHP Intermediate 4 min read

Exception Best Practices

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.

Example
<?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;
}
Pro Tip

An empty catch block is one of the most dangerous things in PHP — always at minimum log the exception.