CKTIS / PHP
DomainException
DomainException est une LogicException pour une valeur hors du domaine de l’opération.
Version : PHP 8.4; repository runtime, production runtime not attested
Syntaxe
throw new DomainException("outside scale")DomainException est une LogicException pour une valeur hors du domaine de l’opération. La fonction accepte les entiers de 0 à 100 inclus et rejette explicitement 101. Une chaîne échoue plus tôt au contrôle strict de type avec TypeError. Le type int seul ne fixe pas l’intervalle.
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
Exemples
<?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;
}
Résultat
0 100 DomainException TypeError