Kyle Thomas Kyle Thomas - 1 year ago 57
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) {

Suggestions? - I have read documentation and found nothing.

Answer Source

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


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();



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


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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download