Base de connaissancesCentre d’examen
FRFrançais
Choisir la langue13

CKTIS / PHP

OutOfBoundsException

OutOfBoundsException dérive de RuntimeException pour un indice ou une clé invalide.

Version : PHP 8.4; repository runtime, production runtime not attested

Syntaxe

throw new OutOfBoundsException("index missing")

OutOfBoundsException dérive de RuntimeException pour un indice ou une clé invalide. Une collection peut la lever après vérification, tandis que lire une clé absente d’un tableau ordinaire en PHP 8.4 émet un avertissement et donne null. La fonction array_key_exists distingue une valeur null enregistrée d’une clé absente.

function fetchRow(array $rows, int $i): mixed {
    if (!array_key_exists($i, $rows)) { throw new OutOfBoundsException("index " . $i); }
    return $rows[$i];
}
var_dump(fetchRow([null], 0));
try { fetchRow([null], 1); }
catch (OutOfBoundsException $e) { echo get_class($e), " ", $e->getMessage(); }
NULL
OutOfBoundsException index 1

Exemples

<?php
function fetchRow(array $rows, int $i): mixed {
    if (!array_key_exists($i, $rows)) { throw new OutOfBoundsException("index " . $i); }
    return $rows[$i];
}
var_dump(fetchRow([null], 0));
try { fetchRow([null], 1); }
catch (OutOfBoundsException $e) { echo get_class($e), " ", $e->getMessage(); }

Résultat

NULL
OutOfBoundsException index 1

Sources