Base de conhecimentoCentro de Exames
PT · PTPortuguês (Portugal)
Escolher idioma13

CKTIS / PHP

OutOfBoundsException

OutOfBoundsException deriva de RuntimeException para um índice ou chave inválidos.

Versão: PHP 8.4; repository runtime, production runtime not attested

Sintaxe

throw new OutOfBoundsException("index missing")

OutOfBoundsException deriva de RuntimeException para um índice ou chave inválidos. Uma coleção pode lançá-la ao verificar limites, mas ler uma chave ausente de um array normal em PHP 8.4 emite um aviso e dá null. A função array_key_exists distingue null guardado de uma chave ausente.

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

Exemplos

<?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(); }

Resultado

NULL
OutOfBoundsException index 1

Fontes