Znalostná bázaCentrum skúšok
SKSlovenčina
Vybrať jazyk13

CKTIS / PHP

RuntimeException

RuntimeException opisuje zlyhanie zistené za behu, napríklad nečakaný koniec prúdu.

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

Syntax

throw new RuntimeException("missing header")

RuntimeException opisuje zlyhanie zistené za behu, napríklad nečakaný koniec prúdu. Dedí od Exception a môže niesť správu, kód a predchádzajúci Throwable. Funkcia vracajúca false výnimku sama nevytvorí. Príklad výslovne premení koniec prúdu na chybu a zachová platný prázdny riadok.

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

Prí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ýsledok

""
7 missing header

Zdroje