PHP try-catch not working

PHP try-catch not working

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

PHP try-catch not working: Understanding Scope and Error Types

When migrating from C# to PHP, one of the most jarring differences you'll encounter is how exceptions behave relative to control flow. In your specific case, the try block isn't "failing" in the way you expect because the error occurring inside the loop is a warning, not an exception, and the variable binding logic differs significantly between the two languages.

The core issue lies in the interaction between the database query result and the mysqli_fetch_array function. In your code snippet, the variable $matrix holds the return value of Query::take(). If that query executes successfully but returns zero rows, or if the underlying database connection fails silently (depending on your configuration), $matrix might be null or an empty object. When you subsequently pass this to mysqli_fetch_array, PHP throws a Warning because it expects a mysqli_result resource but receives something else.

In C#, a warning is often treated as an error that halts execution unless explicitly handled, and exceptions are first-class citizens that bubble up immediately. In PHP, however, warnings do not trigger the catch(Exception $e) block by default. The catch clause only intercepts exceptions thrown via the throw keyword or generated by functions like mysqli_query when error reporting is set to treat errors as exceptions (which requires specific configuration). A standard warning simply halts the script execution at that line, preventing it from reaching the return 'something'; statement within the try block. Because the script stops there, the exception handler never gets a chance to run unless the language setting forces warnings into exceptions.

To see why this happens, look closely at the data flow. The function mysqli_fetch_array expects a resource handle returned by a previous SELECT query. If $matrix is null, PHP cannot iterate over it. Instead of wrapping this validation failure in an exception automatically, PHP emits a warning and stops. This behavior is intentional; it allows developers to distinguish between recoverable errors (exceptions) and logic errors or missing data (warnings). If you want the catch block to execute for this specific scenario, you must either convert the warning into an exception using error handling functions or ensure the variable binding never results in a null value.

You can force warnings to become exceptions by configuring your environment. By adding error_reporting(E_ALL | E_STRICT) and setting ini_set('display_errors', 1) alongside ensuring that errors are treated as exceptions, you can make PHP throw an exception when mysqli_fetch_array encounters a null resource. However, relying on this global configuration is often considered a bad practice in production environments because it turns runtime warnings into fatal application stops without giving you a chance to handle the underlying data issue gracefully.

A more robust approach involves checking the state of the database connection and the query result before attempting to fetch rows. You can use mysqli_error() or check the return value of Query::take() to ensure $matrix contains valid data. If the query returns an empty result set, you should handle that specific case inside the logic rather than relying on exception handling for control flow. This separation ensures that your application distinguishes between a database connection failure (which warrants an exception) and a business logic condition where no rows exist (which might just require returning an empty collection).

Furthermore, mixing raw Query objects from a query builder with procedural-style fetch arrays like mysqli_fetch_array can lead to type mismatches. Modern PHP frameworks often encourage using the iterator syntax or converting results to collections before iteration. For instance, iterating over $matrix directly if it returns a collection object avoids the need for explicit resource handling and reduces the risk of null pointer exceptions.

In summary, the catch block failed because the error was emitted as a warning, not an exception. To resolve this, you must either adjust your error reporting settings to treat warnings as exceptions or refactor the code to validate inputs before fetching. Understanding the distinction between warnings and exceptions is crucial for writing stable PHP applications that behave predictably across different environments.

Our network