Skip to content
Exception Handling
step 1/6

Reading — step 1 of 6

Learn

~1 min readModern PHP

PHP exceptions extend \Throwable. Use try/catch/finally:

try {
    $data = parseConfig($input);
} catch (JsonException $e) {
    error_log("bad json: " . $e->getMessage());
    return null;
} catch (\Exception $e) {
    error_log("unexpected: " . $e->getMessage());
    throw $e;       // re-throw
} finally {
    cleanup();
}

Multi-catch (PHP 8+, won't work on 7.4):

try { ... }
catch (TypeError | ValueError $e) { ... }

On 7.4 use a common ancestor:

catch (\RuntimeException $e) { ... }

Custom exceptions — extend \Exception (or \RuntimeException):

class ValidationException extends \Exception {
    public function __construct(
        public string $field,
        string $msg = '',
    ) {
        parent::__construct($msg ?: "missing $field");
    }
}

throw new ValidationException('email');

Useful built-in exceptions:

  • \InvalidArgumentException — bad parameter
  • \OutOfRangeException — index out of bounds
  • \RuntimeException — error at runtime that couldn't be predicted
  • \LogicException — programmer error (should have caught at dev time)

Throwable is the root — both Exception and Error (engine errors like TypeError) implement it. Catch \Throwable only at the topmost layer.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…