Trong các phiên bản PHP trước, chỉ xử lý được ngoại lệ (exceptions). Không thể xử lý lỗi (errors). Trong trường hợp Fatal Error, nó dừng toàn bộ ứng dụng hoặc một phần. Để khắc phục, PHP 7 thêm interface Throwable để xử lý cả exceptions và errors.
Exception: Khi xảy ra lỗi fatal và recoverable, PHP 7 ném exception thay vì dừng toàn bộ ứng dụng hoặc script.
Error: PHP 7 ném TypeError, ArithmeticError, ParserError, AssertionError, nhưng warning và notice không đổi. Dùng try/catch bắt instance error, giờ FatalErrors có thể ném error instance. Trong PHP 7, interface Throwable được thêm để hợp nhất hai nhánh exception: Exception và Error, thực hiện Throwable.
Ví dụ
<?php
class XYZ {
public function Hello() {
echo "class XYZ\n";
}
}
try {
$a = new XYZ();
$a->Hello();
$a = null;
$a->Hello();
}
catch (Error $e) {
echo "Error occurred" . PHP_EOL;
echo $e->getMessage() . PHP_EOL;
echo "File: " . $e->getFile() . PHP_EOL;
echo "Line: " . $e->getLine() . PHP_EOL;
}
echo "Continue the PHP code\n";
?>
Kết quả
class XYZ Error occurred Call to a member function Hello() on null File: /home/cg/root/9008538/main.php Line: 11 Continue with the PHP code
Lưu ý: Trong ví dụ trên, gọi phương thức trên đối tượng null. Catch dùng để xử lý ngoại lệ và tiếp tục code PHP.
Lỗi Toán học (Arithmetic Error)
Sử dụng DivisionByZeroError của arithmetic error. Vẫn nhận warning error trên phép chia.
Ví dụ: arithmetic error
<?php
$x = 10;
$y = 0;
try {
$z = intdiv($x, $y);
}
catch (DivisionByZeroError $e) {
echo "Error has occured\n";
echo $e->getMessage() . PHP_EOL;
echo "File: " . $e->getFile() . PHP_EOL;
echo "Line: " . $e->getLine() . PHP_EOL;
}
echo "$z \n";
echo " continues with the PHP code\n";
?>
Kết quả
Division by zero File: /home/cg/root/9008538/main.php Line: 5 continues with the PHP code
Lưu ý: Trong chương trình trên, bắt và báo cáo DivisionByZeroError bên trong hàm intdiv().