Error Class in PHP: Hierarchy, Examples

The Error class was introduced in PHP 7, which is the base class for all internal PHP errors. It allows you to handle many fatal errors using a try-catch block that occur during script execution.

With the introduction of the Error class in PHP 7 and later versions, error handling became more powerful and structured.

Before PHP 7, many fatal errors would simply stop script execution without providing sufficient information about them or allowing developers to handle them properly.

Hierarchy of Error Class in PHP


The Error class implements the built-in Throwable interface. The Throwable interface is the base interface for the Exception and Error classes. The hierarchy diagram of the Error class in PHP is given below.

Diagram of hierarchy Error class in PHP.

Subclasses of Error in PHP


The Error class in PHP is the base class for several subclasses:

  • TypeError
  • ParseError
  • ArithmeticError
  • DivisionByZeroError
  • ArgumentCountError
  • ValueError (PHP 8+)
  • UnhandledMatchError (PHP 8+)

Let’s understand each one with examples.

1. TypeError

The TypeError in PHP is a subclass of Error class that is thrown when

  • An argument passed to a function does not match its corresponding declared parameter type.
  • A value returned from a function does not match the declared return type.
  • A value assigned to a class property does not match the property’s declared type.

Example 1: Invalid Argument Type

<?php
declare(strict_types=1);
function add(int $a, int $b) {
   return $a + $b;
}
try {
// Passing the first argument of string type instead of int.
   echo add("10", 5);
} catch (TypeError $e) {
    echo "Type Error: " . $e->getMessage();
}
?>

Output:

Type Error: add(): Argument #1 ($a) must be of type int, string given

In this example, when declare(strict_types=1); is enabled, PHP uses strict type checking. In strict mode, a TypeError is thrown if the argument type does not exactly match the declared parameter type.

Without declare(strict_types=1);, PHP uses type coercion (weak typing). This means PHP automatically converts compatible scalar types. For example, the string “10” is automatically converted into the integer 10, so the output will be 15. By default, PHP runs in weak (coercive) typing mode, which allows automatic type conversion for scalar values.

Example 2: Return Type Mismatch

<?php
function getNumber(): int {
   return "Hello";
}
try {
   echo getNumber();
} catch (TypeError $e) {
     echo "Return Type Error: " . $e->getMessage();
}
?>

Output:

Return Type Error: getNumber(): Return value must be of type int, string returned

2. ParseError

A ParseError in PHP occurs when the parser is unable to parse the code due to syntax errors. It usually happens at compile time, stopping the script’s execution immediately. When a ParseError occurs, the PHP error message typically provides the filename and the line number where the issue was detected.


Parse errors are almost always caused by simple syntax mistakes in the code. Common reasons include:

  • Missing semicolons (;) at the end of statements.
  • Unclosed quotes (single ‘ or double “).
  • Mismatched parentheses () or braces {}.
  • Missing operators for string concatenation.

Example 3:

<?php
function greet($name) {
   echo "Hello " . $name;
// Missing closing brace here.
echo greet("John");
?>

Output:

Parse error: syntax error, unexpected end of file

In this example:

  • The function greet() is opened with the opening curly brace ({), but the closing brace (}) is missing.
  • Because of this, PHP cannot properly understand where the function ends.
  • The PHP parser detects a syntax error before execution. The script stops immediately and the PHP displays the ParseError message.
  • This error occurs before the script runs.
  • Since the script fails before execution begins, the try-catch block never runs. Therefore, the ParseError cannot be caught directly with try-catch block.
  • To catch it, we must make the syntax error occur at runtime and that is done using eval() function.
  • Using eval() function allows the parse error to occur at runtime. This makes it possible to handle the error using a try-catch block.

Example 4: ParseError Handled Using eval() Function

<?php
$code = '
function greet($name) {
     echo "Hello " . $name;
echo greet("John");
';

try {
   eval($code);
} catch (ParseError $e) {
     echo "Caught ParseError: " . $e->getMessage();
}
?>

Output:

Caught ParseError: syntax error, unexpected end of file

In this example:

  • We have stored the code inside a string variable named $code.
  • The function greet() is missing a closing brace (}).
  • The eval() function inside the try block tries to execute the string as PHP code.
  • The parser detects a syntax error at runtime. Therefore, PHP throws a ParseError.
  • The catch block successfully handles it instead of stopping the script.

3. ArithmeticError

An ArithmeticError in PHP is thrown when an error occurs during certain mathematical operations. This type of error is generated when:

  • A bitwise shift operation is performed with a negative shift value.
  • The intdiv() function is called with a numerator of PHP_INT_MIN and a denominator of -1, because the result would be outside the valid integer range (resulting in integer overflow).

Example 5:

<?php
try {
    echo intdiv(PHP_INT_MIN, -1);
} catch (ArithmeticError $e) {
    echo "Arithmetic Error: " . $e->getMessage();
}
?>

Output:

Arithmetic Error: Division of PHP_INT_MIN by -1 is not an integer

In this example:

  • PHP_INT_MIN is the smallest possible integer value in PHP.
  • If we divide it by -1 using intdiv() function inside the try block, it mathematically produces a number larger than PHP_INT_MAX.
  • The result would exceed the allowed integer range.
  • This causes an integer overflow, and PHP throws an ArithmeticError exception.
  • The catch block handles the error gracefully.

4. DivisionByZeroError

The DivisionByZeroError in PHP is a subclass of ArithmeticError, which extends Error class. It is thrown when an attempt is made to divide a number by zero using the intdiv() function or the modulo (%) operator in PHP 7, and also when using the division (/) operator in PHP 8 and later.

Example 6:

<?php
try {
    echo intdiv(10, 0);
} catch (DivisionByZeroError $e) {
    echo "Division Error: " . $e->getMessage();
}
?>

Output:

Division Error: Division by zero

5. ArgumentCountError

The ArgumentCountError in PHP extends the TypeError class. PHP throws it when a function is called with an incorrect number of arguments (either too few arguments, or too many arguments for certain built-in non-variadic functions). This error was introduced in PHP 7.1.0 to provide a more specific error type than the generic TypeError in strict mode.

Example 7:

<?php
function greet($name) {
   return "Hello " . $name;
}
try {
    echo greet();
} catch (ArgumentCountError $e) {
     echo "Argument Count Error: " . $e->getMessage();
}
?>

Output:

Argument Count Error: Too few arguments to function greet()

6. ValueError

The ValueError, introduced in PHP 8, is a built-in error that is thrown when a function receives an argument of the correct data type but an invalid value. It is a subclass of Error class in PHP.

Example 8:

<?php
try {
    echo str_repeat("Hello", -2);
} catch (ValueError $e) {
     echo "Value Error: " . $e->getMessage();
}
?>

Output:

Value Error: str_repeat(): Argument #2 ($times) must be greater than or equal to 0

In this example:

  • Inside the try block, we have called str_repeat() function, which expects:
    • First argument → string value
    • Second argument → positive integer value
  • But we passed a negative value -2, which is an invalid value.
  • Since the data type is correct (integer), but the value is invalid. Therefore, PHP throws a ValueError.
  • The catch block followed the try block handles this error gracefully.

7. UnhandledMatchError

The UnhandledMatchError is a subclass of Error class, introduced in PHP 8.0. This error is thrown when a match expression does not handle all possible values.

Example 9:

<?php
try {
   $number = 3;
   $result = match ($number) {
      1 => "One",
      2 => "Two",
   // No default case
   };
   echo $result;
} catch (UnhandledMatchError $e) {
     echo "Unhandled Match Error: " . $e->getMessage();
}
?>

Output:

Unhandled Match Error: Unhandled match value of type int

In this example:

  • The match expression inside the try block checks the value of $number. It handles only two cases: 1 and 2.
  • The value of $number is 3. Therefore, there is no matching case for 3.
  • There is also no default case.
  • PHP throws an UnhandledMatchError error, which is handled by the catch block and displays the message.

Conclusion

The introduction of the Error class in PHP 7 significantly improved error handling in PHP. You can now handle many fatal errors using try-catch blocks, just like exceptions.

The Error class implements the Throwable interface and provides several subclasses, such as TypeError, ParseError, ArithmeticError, and others. We hope you have understood the hierarchy of the Error class in PHP and practiced all the examples provided.

DEEPAK GUPTA

DEEPAK GUPTA

Deepak Gupta is the Founder of Scientech Easy, a Full Stack Developer, and a passionate coding educator with 8+ years of professional experience in Java, Python, web development, and core computer science subjects. With strong expertise in full-stack development, he provides hands-on training in programming languages and in-demand technologies at the Scientech Easy Institute, Dhanbad.

He regularly publishes in-depth tutorials, practical coding examples, and high-quality learning resources for both beginners and working professionals. Every article is carefully researched, technically reviewed, and regularly updated to ensure accuracy, clarity, and real-world relevance, helping learners build job-ready skills with confidence.