3

I get an exception with errorcode 0 but I don't why? The text/message of the exception is "Call to a member function getId() on null" but the attribute "code" is 0. Why is it 0 and not a real number? All other exception has a correct errorcode.

Is it a bug or a misconfiguration in my php.ini?

Has anybody an idea?

5
  • Exception on what part of code? Or function? Commented Sep 14, 2017 at 18:47
  • In a class there is that error and in my own exceptionhandler I want to handle all exceptions which there thrown in my application. In the handler I use $exception->getCode() and $exception->getMessage() Commented Sep 14, 2017 at 18:56
  • Call to member function foo on null is a fatal error. See: stackoverflow.com/questions/277224/… Commented Sep 14, 2017 at 19:00
  • Ah, so I've no chance that a fatal error has a code? or how can I check if it's a fatal error? I use in my fatalhander the function "error_get_last()" but this is always null, but in my old php version 5.6 it works fine :) Commented Sep 14, 2017 at 19:02
  • 1
    You can check that the object you're trying to use, isn't null before using it. If it is, you can throw an exception. Commented Sep 14, 2017 at 19:06

1 Answer 1

7

Exceptions don't always have codes. When one is not explicitly defined, the error code defaults to 0. See http://www.php.net/manual/en/exception.construct.php - an exception will default to a message of "", a code of 0, and a previous exception of NULL.

try {
    throw new Exception('Hello!');
} catch(Exception $e) {
    echo $e->getCode(); // prints 0
}

Same thing with things like PHP errors:

try {
    $foo = new stdClass;
    $foo->fooBar();
} catch(Error $e) {
    echo $e->getCode(); // prints 0 too
    echo $e->getMessage(); // prints "Call to a member function fooBar() on null"
}
Sign up to request clarification or add additional context in comments.

7 Comments

okey, but it in my case it is a php exception, so I hoped that I get an errorCode or an ExceptionType like "E_ERROR". But nothing :)
@user3388366 PHP's built-in Error class has the identical signature. php.net/manual/en/class.error.php The error code for a fatal error appears to be 0.
Ah, so I've no chance that a fatal error has a code? or how can I check if it's a fatal error? I use in my fatalhander the function "error_get_last()" but this is always null, but in my old php version 5.6 it works fine :)
Nice. I didn't realize that was a recoverable error.
Yep, this one's recoverable. I misspoke - you can't catch a fatal error, but this one's non-fatal. Edited an example of it into my answer.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.