PHP: \Exception or Exception inside a namespace

The accepted answer above give the real cause of the issue, but did not answer the topic

If in case someone is interested and is looking for

what is the difference between Exception and \Exception inside a namespace?

Still valid against PHP 7.3.5:

  1. \Exception: Refer to Exception in root namespace
  2. Exception: Refer to Exception in current namespace
  3. PHP does not fall back to root namespace, if the class cannot be found in current name space, it emits an error.

<?php
namespace Business;
try {
    throw new Exception("X"); //  Uncaught Error: Class 'Business\Exception' not found
} catch (Exception $e) {
    echo "Exception: " . $e->getMessage();
}

<?php
namespace Business;
class Exception extends \Exception {} // means \Business\Exception extends \Exception

$a = new Exception('hi'); // $a is an object of class \Business\Exception
$b = new \Exception('hi'); // $b is an object of class \Exception

First of all, you need to understand the difference between an exception and an error:

  1. http://php.net/manual/en/language.exceptions.php
  2. http://php.net/manual/en/ref.errorfunc.php

Trying to foreach over a null value will not yield an exception, but trigger an error. You can use an error handler to wrap an error in an exception, as such:

<?php

function handle ($code, $message)
{
    throw new \Exception($message, $code);
}

set_error_handler('handle');

// now this will fail
try {
    $foo = null;
    foreach ($foo as $bar) {
    }
} catch(\Exception $e) {
    echo $e->getMessage();
}

However in your code, you can simply check if $products is null and if so, throw an exception:

if (!$products) {
    throw new \Exception('Could not find any products')
}
foreach($products as $product) { ...

Tags:

Php

Exception