在 PHP 中,range()
函数用于创建一个包含指定范围内的元素的数组
range()
函数的起始值和结束值是正确的。例如,确保起始值小于或等于结束值,以及确保步长值不为零。function createRange($start, $end, $step = 1) {
if ($start > $end) {
throw new InvalidArgumentException("Start value must be less than or equal to the end value.");
}
if ($step == 0) {
throw new InvalidArgumentException("Step value must not be zero.");
}
return range($start, $end, $step);
}
try {
$range = createRange(1, 10);
foreach ($range as $number) {
echo $number . "\n";
}
} catch (InvalidArgumentException $e) {
echo "Error: " . $e->getMessage();
}
Exception
或其他异常类)。class CustomRangeException extends Exception {
// 添加自定义方法或属性
}
function createRange($start, $end, $step = 1) {
if ($start > $end) {
throw new CustomRangeException("Start value must be less than or equal to the end value.");
}
if ($step == 0) {
throw new CustomRangeException("Step value must not be zero.");
}
return range($start, $end, $step);
}
// 使用自定义异常类
try {
$range = createRange(1, 10);
foreach ($range as $number) {
echo $number . "\n";
}
} catch (CustomRangeException $e) {
echo "Error: " . $e->getMessage();
}
通过这些方法,您可以更好地处理 range()
函数中可能出现的异常情况。