Step 1 of 6 · Reading · ~1 min
Learn
Modern 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 — one block for several unrelated types. It landed in PHP 7.1, so it works on this course's 7.4 grader:
try { ... }
catch (\JsonException | \RuntimeException $e) { ... }
What is not on 7.4 is \ValueError (PHP 8) — reach for \InvalidArgumentException there. When the types you want share a parent, catching the ancestor is still the shorter spelling:
catch (\RuntimeException $e) { ... }
Custom exceptions — extend \Exception (or \RuntimeException):
class ValidationException extends \Exception {
public string $field;
public function __construct(string $field, string $msg = '') {
$this->field = $field;
parent::__construct($msg ?: "missing $field");
}
}
throw new ValidationException('email');
Declaring the property and assigning it in the constructor body looks verbose next to PHP 8's constructor property promotion (__construct(public string $field)) — but promotion is a parse error on 7.4, so this longhand is what the grader accepts.
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…