PHP Error Handling


PHP Error Handling Interview with follow-up questions

1. What is error handling in PHP and why is it important?

Error handling in PHP is the practice of detecting, managing, and responding gracefully to errors and exceptions that occur during script execution. It matters for several reasons:

  • User experience: Unhandled errors expose stack traces and internal paths to users, which is both confusing and a security risk. Proper handling shows user-friendly messages instead.
  • Security: Detailed error messages leaked to the browser can reveal database structure, file paths, and application logic — useful to attackers.
  • Debugging: Structured error logging (to files or services like Sentry) makes it possible to diagnose production issues without exposing information to users.
  • Application stability: Catching expected exceptions and handling them allows the application to recover or degrade gracefully rather than terminating abruptly.

PHP error types:

  • E_ERROR — fatal; script halts
  • E_WARNING — non-fatal; script continues
  • E_NOTICE — informational; script continues
  • E_DEPRECATED — upcoming removal warning

Modern PHP (8.x) approach:

  • Most PHP errors are Error objects or Exception objects that both implement Throwable
  • Use try/catch blocks for predictable failure paths
  • Register a global handler with set_exception_handler() for uncaught exceptions
  • Set display_errors = Off and log_errors = On in production php.ini
  • Use a logging library (Monolog, which powers Laravel and Symfony logging) to send errors to files, Slack, or error tracking services
↑ Back to top

Follow-up 1

Can you explain the different types of errors in PHP?

In PHP, there are three main types of errors:

  1. Syntax errors: These errors occur when the PHP code violates the syntax rules of the language. They are usually caused by missing or misplaced characters, incorrect variable names, or incorrect function usage. Syntax errors prevent the script from running and must be fixed before the script can be executed.

  2. Runtime errors: These errors occur during the execution of a PHP script. They can be caused by various factors such as division by zero, accessing undefined variables or array indexes, or calling undefined functions. Runtime errors can be caught and handled using error handling techniques.

  3. Logical errors: These errors occur when the script does not produce the expected output or behaves unexpectedly. They are not detected by the PHP interpreter and require careful debugging to identify and fix.

Follow-up 2

What is the role of the 'die()' function in error handling?

The 'die()' function in PHP is used to terminate the execution of a script and display a specified error message. It is commonly used for error handling purposes to immediately stop the script when a critical error occurs. The 'die()' function can be useful for debugging and troubleshooting, as it allows developers to quickly identify the cause of the error and display a custom error message to the user.

Follow-up 3

How can we suppress errors in PHP?

In PHP, errors can be suppressed using the '@' symbol before an expression or function call. When the '@' symbol is used, any errors or warnings generated by that expression or function call will be ignored and not displayed. While suppressing errors can be useful in certain situations, it is generally not recommended as it can make it difficult to identify and fix issues in the code. It is better to implement proper error handling techniques and address the errors instead of suppressing them.

Follow-up 4

What is the difference between 'error_reporting(0)' and '@' in PHP?

The 'error_reporting(0)' function in PHP is used to disable error reporting, meaning that no errors or warnings will be displayed. It is commonly used in production environments to prevent error messages from being shown to users.

On the other hand, the '@' symbol is used to suppress errors for a specific expression or function call. It only affects the specific line of code where it is used, and errors or warnings generated by other parts of the script will still be displayed.

While both 'error_reporting(0)' and '@' can be used to suppress errors, it is generally recommended to use 'error_reporting(0)' in production environments and implement proper error handling techniques during development and testing.

2. How can you handle errors in PHP using the try/catch block?

The try/catch block is the standard mechanism for handling exceptions in PHP. Code that might throw an exception goes in the try block; exception handlers go in catch blocks; optional finally runs regardless of outcome.

try {
    $pdo = new PDO('mysql:host=localhost;dbname=app', 'user', 'secret');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $stmt = $pdo->prepare('SELECT * FROM users WHERE id = ?');
    $stmt->execute([$userId]);
    $user = $stmt->fetch();

    if (!$user) {
        throw new RuntimeException("User $userId not found");
    }
} catch (PDOException $e) {
    // Database-specific error
    error_log($e->getMessage());
    throw new RuntimeException('Database error occurred', 0, $e); // wrap and rethrow
} catch (RuntimeException $e) {
    // Application-level error
    echo 'Error: ' . htmlspecialchars($e->getMessage());
} finally {
    // Runs always — good for cleanup (closing resources, logging timing, etc.)
    $pdo = null;
}

Multiple catch blocks: PHP evaluates catch blocks top to bottom; list more specific exceptions before parent classes.

Catching multiple types in one block (PHP 8.0+):

catch (InvalidArgumentException | LengthException $e) {
    // handle both
}

PHP 8.0+ throw as expression:

$user = $result ?? throw new NotFoundException('User not found');

Interview tip: Explain the difference between catching an exception and swallowing it (empty catch blocks hide bugs). Always log, rethrow, or meaningfully handle what you catch.

↑ Back to top

Follow-up 1

What types of exceptions can be caught by the try/catch block?

In PHP, you can catch different types of exceptions using the catch block. By specifying the type of exception in the catch block, you can catch specific exceptions and handle them accordingly. For example:

try {
    // Code that may throw an exception
} catch (InvalidArgumentException $e) {
    // Code to handle InvalidArgumentException
} catch (RuntimeException $e) {
    // Code to handle RuntimeException
} catch (Exception $e) {
    // Code to handle any other exception
}

Follow-up 2

Can you nest try/catch blocks in PHP?

Yes, you can nest try/catch blocks in PHP. This means that you can have a try block inside another try block, and each try block can have its own catch block. This allows you to handle exceptions at different levels of your code. Here is an example of nested try/catch blocks:

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

Follow-up 3

What happens if an exception is not caught?

If an exception is not caught by a catch block, it will cause a fatal error and terminate the script. The error message will be displayed, and any code after the point where the exception was thrown will not be executed. To prevent this, you can use a global exception handler to catch uncaught exceptions and handle them gracefully. Here is an example of a global exception handler:

set_exception_handler(function ($e) {
    // Code to handle the uncaught exception
});

Follow-up 4

Can you explain the 'finally' block in PHP error handling?

In PHP, the 'finally' block is used in conjunction with the try/catch block to specify code that should be executed regardless of whether an exception is thrown or caught. The code in the 'finally' block will always be executed, whether an exception occurs or not. This is useful for performing cleanup tasks or releasing resources. Here is an example:

try {
    // Code that may throw an exception
} catch (Exception $e) {
    // Code to handle the exception
} finally {
    // Code that will always be executed
}

3. What is an Exception in PHP?

An Exception in PHP is an object thrown when an error or unexpected condition occurs during execution, providing a structured, recoverable alternative to fatal errors.

The base class is Exception, which implements the Throwable interface. Key properties and methods:

$e->getMessage()   // Human-readable error description
$e->getCode()      // Optional integer error code
$e->getFile()      // File where the exception was thrown
$e->getLine()      // Line number
$e->getTrace()     // Stack trace as an array
$e->getTraceAsString() // Stack trace as a formatted string
$e->getPrevious()  // Previous exception (for chained exceptions)

The Throwable hierarchy (PHP 7+):

Throwable (interface)
├── Error (engine-level errors: TypeError, ParseError, ArithmeticError, etc.)
└── Exception (application-level exceptions)
    ├── RuntimeException
    ├── InvalidArgumentException
    ├── LogicException
    └── ... (and custom subclasses)

Throwing an exception:

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

PHP 8.0+ throw as expression:

$value = $input ?? throw new InvalidArgumentException('Input required');

Interview note: Know when to use Error vs Exception. TypeError, ValueError (PHP 8.0+), and ArithmeticError are Error subclasses thrown by PHP internals. Application-defined error conditions use Exception or its subclasses.

↑ Back to top

Follow-up 1

How do you throw an exception in PHP?

To throw an exception in PHP, you can use the throw statement followed by an instance of the Exception class or one of its subclasses. For example:

throw new Exception('This is an exception.');

Follow-up 2

Can you create custom exceptions in PHP?

Yes, you can create custom exceptions in PHP by extending the base Exception class or any of its subclasses. This allows you to define your own exception types with custom properties and methods. For example:

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

throw new CustomException('This is a custom exception.');

Follow-up 3

What is the difference between an Error and an Exception in PHP?

In PHP, errors and exceptions are both types of exceptional events, but they are handled differently. Errors are typically caused by mistakes in the code or server configuration and can lead to the termination of the script. Exceptions, on the other hand, are intended to be caught and handled by the script, allowing for graceful error handling and recovery.

Follow-up 4

How can you catch multiple exceptions in PHP?

In PHP, you can catch multiple exceptions using the catch block with multiple catch clauses. Each catch clause specifies the type of exception that it can handle. For example:

try {
    // Code that may throw exceptions
} catch (ExceptionType1 $e) {
    // Handle ExceptionType1
} catch (ExceptionType2 $e) {
    // Handle ExceptionType2
} catch (Exception $e) {
    // Handle any other exceptions
}

4. Can you explain the concept of error reporting in PHP?

Error reporting in PHP controls which categories of errors are generated and where they appear. It is configured via the error_reporting directive and the error_reporting() function.

Error levels (bitmask constants):

E_ERROR        // Fatal — script halts
E_WARNING      // Non-fatal — script continues
E_NOTICE       // Informational (e.g., undefined variable)
E_DEPRECATED   // Feature will be removed in a future version
E_STRICT       // Strict standards suggestions (merged into E_ALL since PHP 7)
E_ALL          // All errors and warnings

Setting error reporting:

// In php.ini
error_reporting = E_ALL
display_errors = Off      // production: never display to browser
log_errors = On
error_log = /var/log/php/error.log

// Programmatically
error_reporting(E_ALL);
ini_set('display_errors', '0');
ini_set('log_errors', '1');
ini_set('error_log', '/var/log/php/error.log');

Development vs production:

  • Development: display_errors = On, error_reporting = E_ALL — see all errors immediately.
  • Production: display_errors = Off, log_errors = On — log errors silently; never expose details to users.

PHP 8.x change: Many constructs that previously generated E_NOTICE or E_WARNING now throw TypeError or ValueError exceptions, making error handling more predictable. For example, passing an argument of the wrong type to a typed function throws TypeError.

Interview tip: Know how to set up structured logging (e.g., Monolog) in a framework so errors are captured in searchable log files or sent to error-tracking services like Sentry.

↑ Back to top

Follow-up 1

How can you set the error reporting level in a PHP script?

You can set the error reporting level in a PHP script using the error_reporting function. This function accepts a bitmask or a named constant representing the desired error reporting level. For example, to enable all error reporting levels except for E_NOTICE and E_STRICT, you can use the following code:

error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);

Follow-up 2

What is the role of the 'display_errors' directive in PHP?

The 'display_errors' directive in PHP determines whether errors should be displayed to the user or not. When 'display_errors' is set to 'On' in the PHP configuration file (php.ini), errors will be displayed. When it is set to 'Off', errors will not be displayed. It is recommended to set 'display_errors' to 'Off' in a production environment to prevent sensitive information from being exposed to users.

Follow-up 3

How can you log errors in PHP?

You can log errors in PHP by configuring the 'error_log' directive in the PHP configuration file (php.ini). The 'error_log' directive specifies the file where error messages should be logged. By default, PHP logs errors to the server's error log file. However, you can also specify a custom file path to log errors to a specific file. For example, to log errors to a file named 'error.log' in the same directory as the PHP script, you can use the following code:

ini_set('error_log', 'error.log');

Follow-up 4

What are the different levels of error reporting in PHP?

PHP provides several levels of error reporting, which determine the types of errors that are reported. The different levels of error reporting in PHP are:

  • E_ERROR: Fatal errors that cause script termination.
  • E_WARNING: Non-fatal errors that do not cause script termination.
  • E_NOTICE: Non-fatal errors that are caused by the script's code.
  • E_PARSE: Compile-time parse errors.
  • E_DEPRECATED: Warnings about deprecated features that will be removed in future versions of PHP.
  • E_STRICT: Suggestions for code improvements to ensure compatibility with future versions of PHP.
  • E_ALL: All errors and warnings, except for E_NOTICE and E_STRICT.

5. What is the role of the 'set_error_handler()' function in PHP?

set_error_handler() registers a custom callback to handle PHP errors (non-exception errors like E_WARNING, E_NOTICE, E_USER_ERROR, etc.) instead of the default PHP error handler.

set_error_handler(function (
    int $errno,
    string $errstr,
    string $errfile,
    int $errline
): bool {
    // Log to a monitoring service or file
    error_log(sprintf(
        "[%s] Error %d: %s in %s on line %d",
        date('Y-m-d H:i:s'), $errno, $errstr, $errfile, $errline
    ));

    // Return false to fall back to PHP's built-in handler
    // Return true to indicate the error was handled
    return true;
}, E_ALL);

Converting errors to exceptions (common pattern):

set_error_handler(function (int $errno, string $errstr, string $errfile, int $errline): never {
    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
});

This allows catching PHP warnings and notices in try/catch blocks.

Limitations:

  • Cannot handle E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR — these are fatal and cannot be recovered from within a custom handler.
  • Use register_shutdown_function() combined with error_get_last() to detect fatal errors at script shutdown.

Related functions:

  • set_exception_handler() — handles uncaught exceptions
  • restore_error_handler() — restores the previous error handler

Interview tip: Frameworks (Laravel, Symfony) install their own error/exception handlers during bootstrap. Understanding this helps when debugging why errors are being captured differently in different environments.

↑ Back to top

Follow-up 1

How can you create a custom error handler in PHP?

To create a custom error handler in PHP, you can define a function that will handle the errors. This function should accept four parameters: error level, error message, error file, and error line. You can then use the 'set_error_handler()' function to set your custom error handler function as the default error handler. Here's an example:

function customErrorHandler($errno, $errstr, $errfile, $errline) {
    // Your error handling code here
}

set_error_handler('customErrorHandler');

Follow-up 2

What are the parameters of the 'set_error_handler()' function?

The 'set_error_handler()' function in PHP accepts a callback function as its parameter. This callback function should accept four parameters: error level, error message, error file, and error line. The error level parameter represents the severity of the error, while the error message parameter contains the error message. The error file parameter represents the file in which the error occurred, and the error line parameter represents the line number at which the error occurred.

Follow-up 3

Can you restore the original error handler after setting a custom one?

Yes, you can restore the original error handler after setting a custom one in PHP. To do this, you can use the 'restore_error_handler()' function. This function restores the default PHP error handler, undoing the effect of the 'set_error_handler()' function. Here's an example:

restore_error_handler();

Follow-up 4

What is the difference between 'set_error_handler()' and 'register_shutdown_function()' in PHP?

The 'set_error_handler()' function in PHP is used to set a user-defined error handler function, which is called when an error occurs. On the other hand, the 'register_shutdown_function()' function is used to register a function that will be called when the script execution ends, whether it ends successfully or due to an error. The main difference is that the error handler set by 'set_error_handler()' is called only when an error occurs, while the function registered with 'register_shutdown_function()' is called regardless of whether an error occurred or not.

Live mock interview

Mock interview: PHP Error 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.