Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

RuntimeException

RuntimeException describes a failure discoverable only while the program runs, such as an unexpectedly exhausted input stream.

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

Syntax

throw new RuntimeException("missing header")

RuntimeException describes a failure discoverable only while the program runs, such as an unexpectedly exhausted input stream. It extends Exception and can carry a message, code and previous Throwable. Library functions that return false do not automatically translate that value into this exception. The example explicitly translates an end-of-stream result and preserves a valid empty line.

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

Examples

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

Result

""
7 missing header

Sources