Znalostní bázeCentrum zkoušek
CSČeština
Vybrat jazyk13

CKTIS / PHP

RuntimeException

RuntimeException popisuje selhání zjištěné za běhu, například nečekaný konec proudu.

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

Syntaxe

throw new RuntimeException("missing header")

RuntimeException popisuje selhání zjištěné za běhu, například nečekaný konec proudu. Dědí od Exception a může nést zprávu, kód a předchozí Throwable. Funkce vracející false výjimku sama nevytvoří. Příklad výslovně převede konec proudu na chybu a zachová platný prázdný řádek.

function headerLine($stream): string {
    $line = fgets($stream);
    if ($line === false) { throw new RuntimeException("missing header", 7); }
    return rtrim($line, "\r\n");
}
$f = fopen("php://memory", "w+"); fwrite($f, "\n"); rewind($f);
echo json_encode(headerLine($f)), PHP_EOL;
try { headerLine($f); }
catch (RuntimeException $e) { echo $e->getCode(), " ", $e->getMessage(); }
fclose($f);
""
7 missing header

Příklady

<?php
function headerLine($stream): string {
    $line = fgets($stream);
    if ($line === false) { throw new RuntimeException("missing header", 7); }
    return rtrim($line, "\r\n");
}
$f = fopen("php://memory", "w+"); fwrite($f, "\n"); rewind($f);
echo json_encode(headerLine($f)), PHP_EOL;
try { headerLine($f); }
catch (RuntimeException $e) { echo $e->getCode(), " ", $e->getMessage(); }
fclose($f);

Výsledek

""
7 missing header

Zdroje