Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
PHP Types of Errors
PHP's internal Error types are represented by classes that are inherited from Error class. The Error class implements Throwable interface and provides a structured way to handle different types of runtime errors.
Error Class Properties
- message − The error message
- code − The error code
- file − The filename where the error happened
- line − The line where the error happened
Error Class Methods
- __construct() − Construct the error object
- getMessage() − Gets the error message
- getPrevious() − Returns previous Throwable
- getCode() − Gets the error code
- getFile() − Gets the file in which the error occurred
- getLine() − Gets the line in which the error occurred
- getTrace() − Gets the stack trace
- getTraceAsString() − Gets the stack trace as a string
- __toString() − String representation of the error
- __clone() − Clone the error
Error Class Hierarchy
Common Error Types
ArithmeticError
Thrown when an error occurs while performing mathematical operations ?
<?php
try {
$result = 1 / 0;
} catch (DivisionByZeroError $e) {
echo "Error: " . $e->getMessage();
}
?>
Error: Division by zero
TypeError
Occurs when a value is not of the expected type ?
<?php
function addNumbers(int $a, int $b): int {
return $a + $b;
}
try {
echo addNumbers("hello", 5);
} catch (TypeError $e) {
echo "Error: " . $e->getMessage();
}
?>
Error: addNumbers(): Argument #1 ($a) must be of type int, string given
ParseError
Thrown when PHP code contains syntax errors. Here's an example of catching parse errors in evaluated code ?
<?php
try {
eval('echo "Missing semicolon"');
} catch (ParseError $e) {
echo "Parse Error: " . $e->getMessage();
}
?>
Parse Error: syntax error, unexpected end of file
Conclusion
PHP's Error class hierarchy provides a structured approach to error handling with specific error types for different scenarios. Understanding these error types helps in writing more robust PHP applications with proper exception handling.
Advertisements
