Theory
Error & Exception Handling
PHP 8.3.8
Advanced

Error & Exception Handling

Topic 12 of 13
PHP
<?php
// try / catch / finally
try {
    $result = riskyOperation();
} catch (InvalidArgumentException $e) {
    echo "Invalid: " . $e->getMessage();
} catch (Throwable $t) {
    error_log($t->getMessage());
} finally {
    // Always runs (cleanup, close DB, etc.)
}

// Custom exception
class ValidationException extends RuntimeException {
    public function __construct(
        private readonly array $errors,
        string $message = 'Validation failed'
    ) {
        parent::__construct($message);
    }
    public function getErrors(): array {
        return $this->errors;
    }
}

// Global handler
set_exception_handler(function(Throwable $e) {
    http_response_code(500);
    echo json_encode(['error' => $e->getMessage()]);
});