CMS Drupal Mastering Development

Trying to get property of non-object throws exception that cannot be handled

In a custom Drupal 8 module I decided to wrap a line of code in a try…catch block, in case $node was null.

I understand that in php errors and exceptions are different, and according to Error message – Trying to get property of non-object this is an error, so will not be handled by try…catch, and the code should continue to run after the error.

However when this code runs under Drupal 8 the error hander raises an exception. So I added the try…catch block. But the exception is still unhandled crashed the program.

This is a cut-down version of my code:

$node = null;
try {
  // The next line results in an unhandled exception 
  $f = $node->field_example;
} catch (Exception $e) {
  // Never gets here
  watchdog_exception('example', $e);
// Never gets here

Am I missing something? Surely this can’t be the intended behaviour?

Leave a Reply

Your email address will not be published. Required fields are marked *