Kyle Thomas Kyle Thomas - 3 months ago 7
PHP Question

Exception isn't being picked up in catch

I current have a class that holds this method:

public function getUser(
) {
if (!empty($this->UserName)){
return $this->UserName;
} else {
throw new Exception('Empty UserName');
}
}


When I then run this method when the UserName is NOT set, the catch is not picking up the thrown exception, the page just silently dies.

try {
$example = $obj->getUser();
} catch (Exception $ex) {
die($ex->getMessage());
}


Suggestions? - I have read documentation and found nothing.

Answer

This seems to work, I had to recreate what I assumed would be your class.

<?php

class User {
    public $UserName = '';

    public function getUser() {
        if (empty($this->UserName))
            throw new Exception('UserName is empty!');

        return $this->UserName;
    }
}

try {
    $user = (new User())->getUser();
} catch (Exception $e) {
    echo $e->getMessage();
}

?>

Output

I can only assume that your variable is not actually empty.

Notice

In PHP a string with a space in it is NOT classed as empty,

var_dump(empty(' ')); // false

Unless you trim,

var_dump(empty(trim(' '))); // true

Error Reporting

If it isn't done so already, enable error_reporting,

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
Comments