Try/Catch/Finally
try {
\$result = riskyOperation();
if (\$result === false) {
throw new RuntimeException("Operation failed");
}
} catch (RuntimeException \$e) {
echo "Error: " . \$e->getMessage();
} catch (LogicException \$e) {
// Another exception type
} finally {
// Always executed
cleanup();
}Custom Exceptions
class ValidationException extends RuntimeException {
public function __construct(
string \$message,
private array \$errors = [],
int \$code = 422,
?Throwable \$previous = null,
) {
parent::__construct(\$message, \$code, \$previous);
}
public function getErrors(): array {
return \$this->errors;
}
}Multiple Catch
PHP 8.0+ supports catching multiple exceptions in one block: catch (A | B \$e)