CKTIS / PHP
DomainException
DomainException ist eine LogicException für einen Wert außerhalb des Definitionsbereichs.
Version: PHP 8.4; repository runtime, production runtime not attested
Syntax
throw new DomainException("outside scale")DomainException ist eine LogicException für einen Wert außerhalb des Definitionsbereichs. Die Funktion akzeptiert ganze Zahlen von 0 bis einschließlich 100 und weist 101 ausdrücklich zurück. Eine Zeichenkette scheitert zuvor mit TypeError an der strengen Typprüfung. Der Typ int allein legt den Bereich nicht fest.
declare(strict_types=1);
function percent(int $n): int {
if ($n < 0 || $n > 100) { throw new DomainException("outside scale"); }
return $n;
}
foreach ([0, 100, 101, "5"] as $n) {
try { echo percent($n); } catch (DomainException|TypeError $e) { echo get_class($e); }
echo PHP_EOL;
}
0
100
DomainException
TypeError
Beispiele
<?php
declare(strict_types=1);
function percent(int $n): int {
if ($n < 0 || $n > 100) { throw new DomainException("outside scale"); }
return $n;
}
foreach ([0, 100, 101, "5"] as $n) {
try { echo percent($n); } catch (DomainException|TypeError $e) { echo get_class($e); }
echo PHP_EOL;
}
Ergebnis
0 100 DomainException TypeError