Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

UnexpectedValueException

UnexpectedValueException specializes RuntimeException for a value that does not match what a runtime operation expects, often a return value from another component.

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

Syntax

throw new UnexpectedValueException("invalid status")

UnexpectedValueException specializes RuntimeException for a value that does not match what a runtime operation expects, often a return value from another component. The example distinguishes syntactically valid JSON with an unknown status from a JSON decoding error. Valid text alone does not guarantee an allowed value. The program validates the decoded result explicitly.

function status(string $json): string {
    $value = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
    if (!in_array($value, ["open", "closed"], true)) {
        throw new UnexpectedValueException("invalid status");
    }
    return $value;
}
foreach (['"open"', '"other"', '{'] as $raw) {
    try { echo status($raw); } catch (UnexpectedValueException|JsonException $e) { echo get_class($e); }
    echo PHP_EOL;
}
open
UnexpectedValueException
JsonException

Examples

<?php
function status(string $json): string {
    $value = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
    if (!in_array($value, ["open", "closed"], true)) {
        throw new UnexpectedValueException("invalid status");
    }
    return $value;
}
foreach (['"open"', '"other"', '{'] as $raw) {
    try { echo status($raw); } catch (UnexpectedValueException|JsonException $e) { echo get_class($e); }
    echo PHP_EOL;
}

Result

open
UnexpectedValueException
JsonException

Sources