CKTIS / PHP
DomainException
DomainException è una LogicException per un valore esterno al dominio dell’operazione.
Versione: PHP 8.4; repository runtime, production runtime not attested
Sintassi
throw new DomainException("outside scale")DomainException è una LogicException per un valore esterno al dominio dell’operazione. La funzione accetta interi da 0 a 100 inclusi e rifiuta esplicitamente 101. Una stringa fallisce prima nel controllo stretto del tipo con TypeError. Il tipo int da solo non fissa l’intervallo.
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
Esempi
<?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;
}
Risultato
0 100 DomainException TypeError