Docs/PHP/Error Handling

PHP Error Handling

try/catch

  • try — kode yang mungkin error
  • catch (Exception $e) — tangani error
  • finally — selalu jalan
  • throw new Exception() — lempar error

Error Levels

  • E_ERROR — fatal
  • E_WARNING — warning
  • E_NOTICE — notice
index.php
Try It →
<?php
// try/catch
try {
    $result = 10 / 2;
    echo "10 / 2 = $result
";
    
    // This would throw
    // $result = 10 / 0;
} catch (DivisionByZeroError $e) {
    echo "❌ " . $e->getMessage() . "
";
}

// Custom exception
function validateAge(int $age): void {
    if ($age < 0) throw new InvalidArgumentException("Age cannot be negative");
    if ($age > 150) throw new RangeException("Age too high");
    echo "✅ Valid age: $age
";
}

try {
    validateAge(25);
    validateAge(-5);
} catch (InvalidArgumentException $e) {
    echo "❌ Invalid: " . $e->getMessage() . "
";
} catch (RangeException $e) {
    echo "❌ Range: " . $e->getMessage() . "
";
} finally {
    echo "
(finally always runs)";
}
?>