Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> PHP

PHP ArithmeticError

บทนำ

คลาส ArithmeticError สืบทอดมาจากคลาส Error ข้อผิดพลาดประเภทนี้อาจเกิดขึ้นขณะทำ operation คณิตศาสตร์บางอย่าง หนึ่งสถานการณ์คือพยายามทำ bitwise shift operation ด้วยจำนวนลบ ข้อผิดพลาดนี้ยังถูกโยนเมื่อการเรียกฟังก์ชัน intdiv() ให้ผลลัพธ์ที่เกินขอบเขตที่ถูกต้องของ integer

ArithmeticError Example

ในตัวอย่างต่อไปนี้ พยายามใช้ binary shift operator ด้วย operand เป็นลบ ทำให้เกิด ArithmeticError

ตัวอย่าง

<?php try { $a = 10; $b = -3; $result = $a << $b; } catch (ArithmeticError $e) { echo $e->getMessage(); } ?>

ผลลัพธ์

จะได้ผลลัพธ์ดังนี้

Bit shift by negative number

หากการเรียกฟังก์ชัน intdiv() ให้ integer ที่ไม่ถูกต้อง ArithmeticError จะถูกโยน ตามตัวอย่างด้านล่าง integer ต่ำสุดที่อนุญาตใน PHP (PHP_INT_MIN) ไม่สามารถหารด้วย -1 ได้

ตัวอย่าง

<?php try { $a = PHP_INT_MIN; $b = -1; $result = intdiv($a, $b); echo $result; } catch (ArithmeticError $e) { echo $e->getMessage(); } ?>

ผลลัพธ์

จะได้ผลลัพธ์ดังนี้

Division of PHP_INT_MIN by -1 is not an integer