Throwable Interface in PHP | PHP Exception Class

PHP 7 introduced the Throwable interface, which is a base interface for any object that that can be thrown with the throw statement. It is the root of the error and exception hierarchy in modern PHP.

Both built-in Exception and Error classes implement the Throwable interface. This allows you to catch both Exception and Error using a single catch (Throwable $e) block. In simple words, you can catch everything using a single catch (Throwable $e) block.

User-defined exception classes cannot implement Throwable directly. PHP does not allow direct implementation of Throwable in user-defined classes. For example:

class MyException implements Throwable {}

This will cause a fatal error. Instead, to create a custom throwable object, the class must extend Exception which implicitly implements Throwable. For example:

class MyException extends Exception {
}

Since Exception already implements Throwable, so any class extending Exception automatically becomes a Throwable.

PHP Throwable Hierarchy


Here is the complete hierarchy of the Throwable interface in the modern PHP, including built-in Exception and Error classes and their major subclasses. This represents the internal error and exception structure of modern PHP.

Diagram of Throwable hierarchy in PHP

Methods Defined by Throwable Interface in PHP


The Throwable interface in PHP defines several predefined methods that allow developers to retrieve detailed information about errors and exceptions. These methods provide access to error messages, exception codes, file locations, stack traces, and other debugging details.

Since the Exception and Error classes implement the Throwable interface, both can use these predefined methods. The methods declared in the Throwable interface are:

  • getMessage() → Returns the string error or exception message associated with the thrown object.
  • getCode() → Returns the exception/error code.
  • getFile() → Returns the name of the file in which the exception occurred.
  • getLine() → Returns the line number where the exception occurred.
  • getTrace() → Returns the stack trace as an array.
  • getTraceAsString() → Returns the stack trace as a string.
  • getPrevious() → Returns the previous exception used in exception chaining.
  • __toString() → Gets a string representation of the thrown exception.

Exception Class in PHP


The Exception class is a built-in base class for all standard user-defined exceptions in PHP. It is mainly used to handle logical and runtime errors using throw, try, and catch blocks.

[blocksy-content-block id=”12371″]

The Exception class implements the Throwable interface, which is the top-level interface for all throwable objects introduced in PHP 7. The Exception class was introduced in PHP 5 and continues to work in modern PHP versions (PHP 7 and later).

Types of Exception Classes in PHP

PHP provides several built-in subclasses of the Exception class, including:

  • LogicException
  • RuntimeException
  • ErrorException
  • PDOException

PHP LogicException


LogicException is a built-in subclass of the Exception class in PHP. It represents logical errors in PHP programs or incorrect API usage. These errors commonly occur due to programming mistakes rather than external runtime conditions such as file systems or databases. Therefore, programmers should fix these errors by correcting the code.

Types of LogicException in PHP

PHP provides several built-in subclasses of LogicException:

  • BadFunctionCallException
    • BadMethodCallException
  • DomainException
  • InvalidArgumentException
  • LengthException
  • OutOfRangeException

All these exceptions under LogicException belong to the Standard PHP Library (SPL) and are usually thrown manually by developers. Now let’s explain each one with simple examples.

1. BadFunctionCallException

The BadFunctionCallException is a standard built-in subclass of LogicException class. It’s part of the Standard PHP Library (SPL) exceptions. The BadFunctionCallException is thrown when a function is called incorrectly, such as if a callback refers to an undefined function or some arguments are missing.

PHP does not automatically throw BadFunctionCallException. It is typically manually thrown by developers. Undefined functions normally produce a fatal error (Error), not BadFunctionCallException.

Example:

<?php
function greet($name = null) {
   if ($name === null) {
   // Manually throw exception.
      throw new BadFunctionCallException("Name parameter is required.");
   }
   return "Hello, " . $name;
}
try {
   echo greet(); // Missing argument
} catch (BadFunctionCallException $e) {
    echo "Caught: " . $e->getMessage();
}
?>

Output:

Caught: Name parameter is required.

In this example:

  • We have defined a function greet() with a parameter $name.
  • If the argument for $name is not provided, we have thrown BadFunctionCallException.
  • The exception is caught in the catch block, and the error message is displayed.

2. DomainException

The DomainException is a standard built-in subclass of LogicException and is a part of the Standard PHP Library (SPL) exceptions. This exception is manually thrown when an input value does not belong to a valid domain.

Example:

<?php
function setAge($age) {
   if ($age < 0) {
      throw new DomainException("Age cannot be negative.");
   }
}
try {
    setAge(-5);
} catch (DomainException $e) {
     echo $e->getMessage();
}
?>

Output:

Age cannot be negative.

[blocksy-content-block id=”12121″]

3. InvalidArgumentException

The InvalidArgumentException is a standard built-in subclass of LogicException and is part of the Standard PHP Library (SPL) exceptions. This exception is manually thrown when a function receives an invalid argument.

Example:

<?php
function setAge($age) {
   if (!is_int($age)) {
      throw new InvalidArgumentException("Age must be an integer.");
   }
   return "Age set to " . $age;
}
try {
    echo setAge("twenty");
} catch (InvalidArgumentException $e) {
     echo $e->getMessage();
}
?>

Output:

Age must be an integer.

4. LengthException

The LengthException is a standard built-in subclass of LogicException in PHP that is manually thrown when the length of data is invalid. It is also part of the Standard PHP Library (SPL) exceptions. You can use this exception when you want to check:

  • String length is too short or too long.
  • Array size is invalid or not.
  • Password length rules are violated or not.

Example: Validating String Length

<?php
function setUsername($username) {
   if (strlen($username) < 5) {
      throw new LengthException("Username must be at least 5 characters long.");
   }
   return "Username accepted: " . $username;
}
try {
   echo setUsername("Tom");
} catch (LengthException $e) {
     echo $e->getMessage();
}
?>

Output:

Username must be at least 5 characters long.

5. OutOfRangeException

The OutOfRangeException is a standard built-in exception which extends LogicException. This exception is thrown manually when a value is outside an allowed range.

Example: Value Outside the Range

<?php
function setLevel($level) {
   if ($level < 1 || $level > 10) {
      throw new OutOfRangeException("Level must be between 1 and 10.");
   }
   return "Level set to " . $level;
}
try {
 // Passing value is outside the allowed range.
    echo setLevel(15);
} catch (OutOfRangeException $e) {
      echo "Caught: " . $e->getMessage();
}
?>

Output:

Caught: Level must be between 1 and 10.

PHP RuntimeException


RuntimeException is a built-in exception class in PHP that extends the base Exception class. This exception represents errors that occur during the execution of program at runtime.

These errors are not caused by programming logic mistakes, but by external or environmental factors. It is part of the Standard PHP Library (SPL). Like other SPL exceptions, PHP does not automatically throw RuntimeException; developers throw it explicitly.
[blocksy-content-block id=”12153″]

Types of RuntimeException in PHP

PHP provides several built-in subclasses of RuntimeException. They are:

  • BadMethodCallException
  • OutOfBoundsException
  • OverflowException
  • UnderflowException
  • UnexpectedValueException

Most exceptions under RuntimeException belong to the Standard PHP Library (SPL) and are usually thrown manually by developers. Let us discuss each one by one with examples.

1. BadMethodCallException

The BadMethodCallException is a standard built-in exception in PHP that extends RuntimeException. This exception is manually thrown by developer when an invalid or undefined method is called.

PHP does not automatically throw BadMethodCallException. The BadMethodCallException is commonly used with magic methods, such as __call() or __callStatic().

Example:

<?php
class Calculator {
   public function add($a, $b) {
      return $a + $b;
   }
   public function __call($name, $arguments) {
      throw new BadMethodCallException("Method '$name' does not exist.");
   }
}
try {
   $calc = new Calculator();
   echo $calc->multiply(2, 3);
} catch (BadMethodCallException $e) {
    echo "Caught: " . $e->getMessage();
}
?>

Output:

Caught: Method 'multiply' does not exist.

In this example:

  • The Calculator class defines only the add() method. It does not define multiply() method.
  • Calling multiply() from inside the try block triggers the __call() magic method.
  • Inside __call() method, we manually throw BadMethodCallException.
  • The exception is caught and handled safely by catch block.

2. OutOfBoundsException

OutOfBoundsException is a standard built-in exception in PHP’s Standard PHP Library (SPL) that extends RuntimeException.  The OutOfBoundsException is thrown when an invalid index or key is used to access an array, collection, or other data structure. This exception can be thrown by PHP internally or manually by a developer.

Example:

<?php
function getElement($array, $index) {
  if (!array_key_exists($index, $array)) {
     throw new OutOfBoundsException("Invalid index: $index");
  }
  return $array[$index];
}
try {
   $numbers = [10, 20, 30];
   echo getElement($numbers, 5); // Invalid index
} catch (OutOfBoundsException $e) {
    echo "Error: " . $e->getMessage();
}
?>

Output:

Error: Invalid index: 5

3. OverflowException

OverflowException is a built-in exception in Standard PHP Library that is a subclass of RuntimeException. It is used when an operation attempts to add or store data that exceeds the allowed storage limit or capacity of a container or data structure.

This exception is usually thrown manually by developers or by certain SPL classes to indicate that a container class, buffer, or collection has reached its maximum capacity.

Example:

<?php
class LimitedBox {
   private $items = [];
   private $limit = 2;

   public function addItem($item) {
     if (count($this->items) >= $this->limit) {
        throw new OverflowException("Box is full. It cannot add more items.");
     }
     $this->items[] = $item;
   }
}
try {
   $box = new LimitedBox();
   $box->addItem("Book");
   $box->addItem("Pen");
   $box->addItem("Notebook"); // This will cause OverflowException.
} catch (OverflowException $e) {
      echo $e->getMessage();
}
?>

Output:

Box is full. It cannot add more items.

4. UnderflowException

UnderflowException is a built-in exception in PHP’s Standard PHP Library (SPL). It is a subclass of RuntimeException. This exception is used when you try to remove or access data from an empty container, such as an empty stack, queue, or collection.

Example:

<?php
$items = [];
try {
   if (empty($items)) {
     throw new UnderflowException("No items to remove.");
   }
   array_pop($items);
} catch (UnderflowException $e) {
    echo $e->getMessage();
}
?>

Output:

No items to remove.

5. UnexpectedValueException

UnexpectedValueException is a built-in exception in PHP’s Standard PHP Library that extends RuntimeException. This exception is used when a function returns a value that is valid in type but unexpected in content.

Example:

<?php
function checkStatus() {
   return "unknown"; // Unexpected value
}
try {
   $status = checkStatus();
   if ($status !== "success" && $status !== "failed") {
      throw new UnexpectedValueException("Unexpected status value: $status");
   }
} catch (UnexpectedValueException $e) {
     echo $e->getMessage();
}
?>

Output:

Unexpected status value: unknown

ErrorException in PHP


ErrorException is a built-in exception in PHP that extends the base Exception class. It is used to convert PHP errors, such as warnings or notices, into exceptions. PHP does not throw this exception automatically. It is usually thrown manually by developers using try-catch blocks.

Example:

<?php
// Convert PHP errors into ErrorException.
set_error_handler(function($severity, $message, $file, $line) {
    throw new ErrorException($message, 0, $severity, $file, $line);
});

try {
// Trying to open a file that does not exist.
   fopen("missing_file.txt", "r");
} catch (ErrorException $e) {
     echo "Error: " . $e->getMessage();
}
?>

Output:

Error: fopen(missing_file.txt): Failed to open stream: No such file or directory

In this example:

  • The fopen() normally generates a PHP warning if the file does not exist.
  • The set_error_handler() converts that warning into an ErrorException.
  • The try-catch block then handles the error safely.

PDOException in PHP


PDOException is a built-in exception in PHP that is thrown when an error occurs during PDO (PHP Data Objects) database operations. It extends the base Exception class. This exception is used to handle errors related to database connections, queries, or transactions when using PDO.

Example:

<?php
try {
// Wrong database name to trigger exception.
   $pdo = new PDO("mysql:host=localhost;dbname=wrong_db", "root", "");
   echo "Connected successfully";
} catch (PDOException $e) {
     echo "Database Error: " . $e->getMessage();
}
?>

Output:

Database Error: SQLSTATE[HY000] [1049] Unknown database 'wrong_db'

In this example:

  • The code inside the try block tries to connect to a database using PDO.
  • Since the database name is incorrect, PDO throws PDOException.
  • The catch block catches it and displays the error message.
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.