Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> PHP

Xử lý ngoại lệ với nhiều catch block trong PHP

Giới thiệu

PHP cho phép một chuỗi các catch block theo sau try block để xử lý các trường hợp exception khác nhau. Các catch block khác nhau có thể dùng để xử lý exception/Error định nghĩa sẵn cũng như user-defined exception.

Ví dụ

Ví dụ sau dùng catch blocks xử lý DivisionByZeroError, TypeError, ArgumentCountError, InvalidArgumentException. Cũng có catch block cho Exception chung.

<?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) {
    echo $x->getMessage();
}
catch (DivisionByZeroError $y) {
    echo $y->getMessage();
}
catch (ArgumentCountError $z) {
    echo $z->getMessage();
}
catch (InvalidArgumentException $i) {
    echo $i->getMessage();
}
catch (Exception $ex) {
    echo $ex->getMessage();
}
?>

Kết quả các trường hợp

Ban đầu $b=0: DivisionByZeroError

Division by zero.

Đặt $b=3: TypeError vì divide() trả về int nhưng chia ra float

Return value of divide() must be of the type integer, float returned

Truyền 1 tham số cho divide(): ArgumentCountError

Too few arguments to function divide(), 1 passed ... and exactly 2 expected

Đối số không phải integer: InvalidArgumentException

Invalid type of arguments