소개
PHP는 try 블록 다음에 오는 일련의 catch 블록을 허용하여 다양한 예외 사례를 처리할 수 있습니다. 사전 정의된 예외 및 오류는 물론 사용자 정의 예외를 처리하기 위해 다양한 catch 블록을 사용할 수 있습니다.
예시
다음 예제에서는 catch 블록을 사용하여 DivisioByZeroError, TypeError, ArgumentCountError 및 InvalidArgumentException 조건을 처리합니다. 일반 예외를 처리하는 catch 블록도 있습니다.
예시
<?php
declare(strict_types=1);
function divide(int $a, int $b) : int {
return $a / $b;
}
$a=10;
$b=0;
try{
if (!$b) {
throw new DivisionByZeroError('Division by zero.');}
if (is_int($a)==FALSE || is_int($b)==FALSE)
throw new InvalidArgumentException("Invalid type of arguments");
$result=divide($a, $b);
echo $result;
}
catch (TypeError $x)//if argument types not matching{
echo $x->getMessage();
}
catch (DivisionByZeroError $y) //if denominator is 0{
echo $y->getMessage();
}
catch (ArgumentCountError $z) //if no.of arguments not equal to 2{
echo $z->getMessage();
}
catch (InvalidArgumentException $i) //if argument types not matching{
echo $i->getMessage();
}
catch (Exception $ex) // any uncaught exception{
echo $ex->getMessage();
}
?> 출력
먼저 분모가 0이므로 0으로 나누기 오류가 표시됩니다.
Division by 0
$b=3으로 설정하면 나누기 함수가 정수를 반환할 것으로 예상되지만 나누기는 부동 소수점이 되기 때문에 TypeError가 발생합니다.
Return value of divide() must be of the type integer, float returned
$res=divide($a); ArgumentCountError
가 발생합니다.Too few arguments to function divide(), 1 passed in C:\xampp\php\test1.php on line 13 and exactly 2 expected
인수 중 하나가 정수가 아니면 InvalidArgumentException의 경우
Invalid type of arguments