PHP Exception Handling


PHP Exception Handling Interview with follow-up questions

1. What is an Exception in PHP?

An Exception in PHP is an object that represents an error or unexpected condition. When thrown, it interrupts normal execution flow and transfers control to the nearest matching catch block, or to the uncaught exception handler if not caught.

class InsufficientFundsException extends RuntimeException {}

function withdraw(float $amount, float $balance): float {
    if ($amount > $balance) {
        throw new InsufficientFundsException(
            "Cannot withdraw $amount; balance is $balance",
            code: 1001
        );
    }
    return $balance - $amount;
}

try {
    $newBalance = withdraw(500, 100);
} catch (InsufficientFundsException $e) {
    echo $e->getMessage(); // "Cannot withdraw 500; balance is 100"
    echo $e->getCode();    // 1001
}

The Throwable hierarchy:

Throwable
├── Error          (engine-level: TypeError, ParseError, ArithmeticError, etc.)
└── Exception      (application-level)
    ├── LogicException        (programming errors detectable before runtime)
    │   ├── InvalidArgumentException
    │   ├── OutOfRangeException
    │   └── BadMethodCallException
    └── RuntimeException      (errors detectable only at runtime)
        ├── OutOfBoundsException
        ├── UnexpectedValueException
        └── OverflowException

PHP 8.x additions:

  • ValueError (PHP 8.0) — thrown when a function argument is of the right type but an invalid value
  • throw as an expression — can be used in match arms, null coalescing, and arrow functions
↑ Back to top

Follow-up 1

How is it different from an error?

An error in PHP is a problem that occurs during the execution of a PHP script and causes the script to stop running. It can be a syntax error, a runtime error, or a logical error. On the other hand, an exception is a way to handle errors or exceptional situations in a controlled manner. When an exception is thrown, it can be caught and handled using try-catch blocks, allowing the script to continue running.

Follow-up 2

Can you explain the concept of exception hierarchy in PHP?

In PHP, exceptions are organized in a hierarchy. The base class for all exceptions is the Exception class. This class provides basic functionality for creating and handling exceptions. You can create custom exception classes by extending the Exception class. These custom exception classes can be used to handle specific types of exceptions or to provide additional information about the exception. By organizing exceptions in a hierarchy, you can catch specific types of exceptions and handle them differently based on their type.

Follow-up 3

What happens if an exception is not caught or handled?

If an exception is not caught or handled, it will result in a fatal error and the script will stop executing. The error message will be displayed to the user, revealing sensitive information about the script. To prevent this, it is important to always catch and handle exceptions using try-catch blocks. This allows you to gracefully handle exceptions and provide appropriate error messages or perform specific actions when an exception occurs.

2. How can you handle exceptions in PHP?

PHP handles exceptions using try/catch/finally blocks. Code that might throw is placed in try; exception handlers in catch; cleanup code in finally.

Basic pattern:

try {
    $result = riskyOperation();
} catch (SpecificException $e) {
    // handle specific case
    logError($e);
} catch (AnotherException | YetAnotherException $e) {
    // catch multiple types in one block (PHP 8.0+)
    notifyAdmin($e);
} catch (\Throwable $e) {
    // catch any Error or Exception — use as a last resort
    throw $e; // re-throw rather than swallowing
} finally {
    // runs regardless of whether an exception was thrown or caught
    cleanup();
}

Catching Throwable vs Exception:

  • Exception — catches only application-level exceptions
  • Throwable — catches both Exception and Error (PHP engine errors like TypeError, Error, etc.)
  • In most application code, catching Exception is appropriate. Use Throwable in framework-level code or global handlers.

Re-throwing with context (exception chaining):

try {
    $pdo->query($sql);
} catch (PDOException $e) {
    throw new RepositoryException('Failed to fetch user', previous: $e);
}

The getPrevious() method retrieves the original cause, preserving the full chain for debugging.

Global exception handler:

set_exception_handler(function (\Throwable $e): void {
    error_log($e->getMessage());
    http_response_code(500);
    echo 'An error occurred.';
});
↑ Back to top

Follow-up 1

What is the syntax of a try-catch block in PHP?

The syntax of a try-catch block in PHP is as follows:

try {
    // code that may throw an exception
} catch (ExceptionType $e) {
    // code to handle the exception
}

Follow-up 2

Can you nest try-catch blocks in PHP?

Yes, it is possible to nest try-catch blocks in PHP. This means that a try block can contain another try-catch block within it. This allows for more granular exception handling and the ability to handle different types of exceptions at different levels of the code.

Follow-up 3

What is the role of the finally block in exception handling?

The finally block in exception handling is used to specify code that should be executed regardless of whether an exception is thrown or not. This block is optional and is placed after the catch block. The code inside the finally block will always be executed, even if an exception is thrown and caught.

3. What is the purpose of the throw keyword in PHP?

The throw keyword raises an exception, immediately interrupting the current execution path and transferring control to the nearest enclosing catch block.

function divide(int $a, int $b): float {
    if ($b === 0) {
        throw new DivisionByZeroError('Cannot divide by zero');
    }
    return $a / $b;
}

PHP 8.0: throw as an expression Before PHP 8.0, throw was a statement and could only appear on its own line. PHP 8.0 made throw an expression, enabling its use in:

  • Null coalescing:

    $user = findUser($id) ?? throw new NotFoundException("User $id not found");
    
  • Ternary:

    $value = $validated ? $input : throw new InvalidArgumentException('Invalid');
    
  • Match arms:

    $status = match($code) {
      200 => 'OK',
      404 => 'Not Found',
      default => throw new UnexpectedValueException("Unknown code: $code"),
    };
    
  • Arrow functions:

    $mustExist = fn($v) => $v ?? throw new RuntimeException('Required');
    

Re-throwing:

catch (PDOException $e) {
    throw new RepositoryException('DB error', previous: $e); // wraps original
}

Interview note: Know when to throw vs return a special value. throw is appropriate for exceptional conditions (programming errors, resource unavailability). Returning null or false is appropriate when "no result" is a normal, expected outcome.

↑ Back to top

Follow-up 1

Can you throw an exception without catching it?

Yes, it is possible to throw an exception without catching it. If an exception is thrown and not caught, it will propagate up the call stack until it reaches a catch block that can handle it. If no catch block is found, a fatal error will occur and the script will terminate.

Follow-up 2

What types of values can be thrown as exceptions?

In PHP, any value can be thrown as an exception, but it is recommended to throw objects that are instances of the built-in Exception class or its subclasses. This allows for more meaningful and structured exception handling. However, it is also possible to throw scalar values like strings or integers as exceptions.

4. How can you create custom exceptions in PHP?

Create a custom exception by extending Exception or a more specific subclass. This allows callers to catch your specific exception type separately from generic ones.

// Define custom exceptions
class UserNotFoundException extends RuntimeException {}

class ValidationException extends InvalidArgumentException {
    /** @param array $errors */
    public function __construct(
        private array $errors,
        string $message = 'Validation failed',
        int $code = 422,
        ?\Throwable $previous = null,
    ) {
        parent::__construct($message, $code, $previous);
    }

    /** @return array */
    public function getErrors(): array {
        return $this->errors;
    }
}

Usage:

function findUser(int $id): User {
    $user = $this->repository->find($id);
    if (!$user) {
        throw new UserNotFoundException("User with ID $id does not exist", 404);
    }
    return $user;
}

try {
    $user = findUser(99);
} catch (UserNotFoundException $e) {
    http_response_code($e->getCode());
    echo $e->getMessage();
}

// ValidationException with structured error data
try {
    validate($input);
} catch (ValidationException $e) {
    return response()->json(['errors' => $e->getErrors()], 422);
}

Best practices:

  • Extend the most specific standard exception that fits (e.g., InvalidArgumentException, RuntimeException, OverflowException)
  • Use custom exception classes rather than passing error codes in generic exceptions — callers can catch by type
  • Add domain-specific methods (like getErrors()) to carry structured failure data
↑ Back to top

Follow-up 1

Why might you want to create a custom exception?

There are several reasons why you might want to create a custom exception in PHP:

  1. Custom error handling: By creating custom exceptions, you can define how specific errors or exceptional situations should be handled in your application.

  2. Better error reporting: Custom exceptions can provide more detailed information about the error, making it easier to debug and fix issues.

  3. Code organization: Creating custom exceptions allows you to organize your code better by grouping related exceptions together.

  4. Application-specific logic: Custom exceptions can be used to implement application-specific logic, such as triggering specific actions or workflows when certain exceptions occur.

Follow-up 2

What is the structure of a custom exception class?

A custom exception class in PHP follows the same structure as any other class. It typically extends the Exception class or one of its subclasses and may include additional properties and methods specific to the exception.

Here's an example of the structure of a custom exception class:

class CustomException extends Exception {
    // Custom properties and methods go here
}

5. What is the difference between Exception and ErrorException in PHP?

Both Exception and ErrorException extend the Exception base class and implement Throwable, but they serve different purposes:

Exception The base class for all application-level exceptions in PHP. Used for expected, recoverable error conditions in your own code.

throw new RuntimeException('File not found');
throw new InvalidArgumentException('Age must be positive');

ErrorException A bridge class that wraps PHP's native error system (warnings, notices, etc.) as catchable exceptions. It adds an $severity parameter mapping to the PHP error level constant.

// Convert PHP warnings/notices to exceptions
set_error_handler(function (int $errno, string $errstr, string $errfile, int $errline): bool {
    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
});

try {
    $result = file_get_contents('/nonexistent/file.txt'); // triggers E_WARNING
} catch (ErrorException $e) {
    echo "Caught: " . $e->getMessage();
    echo "Severity: " . $e->getSeverity(); // E_WARNING = 2
}

Key difference:

Exception ErrorException
Use case Application logic errors Wrapping PHP engine errors
Extra method getSeverity() returns the PHP error level
Thrown by Developer code set_error_handler() converter

PHP 8.x context: Many PHP errors that previously only generated E_WARNING or E_NOTICE now throw actual Error subclasses (TypeError, ValueError). The need for ErrorException wrappers is diminishing, but the pattern is still common in legacy codebases and libraries.

↑ Back to top

Follow-up 1

When would you use ErrorException instead of Exception?

You would use ErrorException instead of Exception when you want to catch and handle PHP errors as exceptions. By default, PHP handles errors using the error handling mechanism defined by the developer, which usually involves displaying an error message and terminating the script. However, if you want to handle these errors in a more controlled manner, you can use the ErrorException class.

By catching PHP errors as exceptions, you can handle them using try-catch blocks and exception handling techniques. This allows you to gracefully handle errors, log them, or take any other action that you would normally take with exceptions.

Here is an example of how you can catch and handle a PHP error using the ErrorException class:

try {
    // Code that may generate an error
} catch (ErrorException $e) {
    // Handle the error as an exception
}

Follow-up 2

How can you convert errors into exceptions using ErrorException?

To convert errors into exceptions using the ErrorException class, you need to set an error handler that throws an ErrorException whenever an error occurs. This can be done using the set_error_handler() function.

Here is an example of how you can convert errors into exceptions using the ErrorException class:

// Define a custom error handler
function errorHandler($severity, $message, $file, $line) {
    throw new ErrorException($message, 0, $severity, $file, $line);
}

// Set the custom error handler
set_error_handler('errorHandler');

try {
    // Code that may generate an error
} catch (ErrorException $e) {
    // Handle the error as an exception
}

Live mock interview

Mock interview: PHP Exception Handling

Intermediate ~5 min Your own free AI key

Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.