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

Error ArithmeticError AssertionError CompileError TypeError DivisionByZeroError ParseError ArgumentCountError Legend: Base Error Class Main Error Types Specific Error Types

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.

Updated on: 2026-03-15T09:23:04+05:30

480 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements