-1

I have a class named User that calls one of its own methods, setUsername(), upon construction, within a try/catch block. If setUsername() fails, it will throw an exception:

class User {
    private $username;

    public function __construct($input_username) {
        try {
            $this->setUsername($input_username);
        } catch(Exception $e) {
            throw $e;
        }
    }

    private function setUsername($username) {
      if(1 != 0)
         throw new Exception("1 does not equal 0!!!");
      $this->username = $username;
    }

}

I then create a new User in an external function, in a separate file, within its own try/catch block. It's supposed to catch the exception passed through from the User class constructor:

namespace UserController;

function createUser(){
    try {
        $user = new \User('sample-user');
    } catch(Exception $e) {
        echo $e->getMessage();
    }
}

Why, then, am I still getting an "Uncaught Exception" error?

fswebb
  • 13
  • 4
  • 2
    Try replacing all instances of `Exception` with `\Exception`. My guess is the code that instantiates the user is in a namespace, which means `Exception` refers to a non-existing class within that namespace. – Jeto Mar 20 '18 at 21:01
  • Shouldn't it be `echo $e->getMessage();`? – Barmar Mar 20 '18 at 21:07
  • @Jeto -- You're correct. The code instantiating the user is in a namespace. I just added that to my question. However, it doesn't seem to have rectified the issue – fswebb Mar 20 '18 at 21:11
  • You forgot a ";" after `throw new Exception("1 does not equal 0!!!")` – Felippe Duarte Mar 20 '18 at 21:12
  • @Felippe Duarte -- Yes, there should be a semicolon there. Whoops. – fswebb Mar 20 '18 at 21:15
  • @Barmar -- Yes, it should. I've fixed that as well. It doesn't solve this issue, but is a bug. Thanks. – fswebb Mar 20 '18 at 21:16
  • @fswebb There is no way a code wrapped in `try` => `catch (\Exception $e)` would generate an `Uncaught Exception` error, since this is the base class of all exceptions. Are you sure you replaced it there? – Jeto Mar 20 '18 at 21:16
  • @Jeto -- I'm sure. I ended up having to add an `use \Exception;` statement right under the namespace declaration. I truly, truly appreciate your help here. – fswebb Mar 20 '18 at 21:25
  • @fswebb That's really weird, and doesn't sound right. But glad you solved it I guess :) – Jeto Mar 20 '18 at 21:27
  • Possible duplicate of [PHP Fatal error: Uncaught Error: Class 'Facebook\WebDriver\ChromeOptions' not found](https://stackoverflow.com/questions/47767408/php-fatal-error-uncaught-error-class-facebook-webdriver-chromeoptions-not-fo) – yivi Mar 21 '18 at 07:02

1 Answers1

0

It seems I was missing a statement at the top of the file that instantiates the class, since it is namespaced. After the namespace declaration, it needs to say:

use \Exception;
fswebb
  • 13
  • 4