PHP – How to catch a 'Trying to get property of non-object' error

I am trying to catch ‘Trying to get property of non-object’ error with a try/catch statement but it is failing, I still get a PHP error. I am using as:

try{
  $id = Model()->find('id=1')->id;
}catch(Exception $e){
  echo 'failed';
}

My find function returns an object (Active Record) and I can access the id column as shown via object prop.

However, it will be null object if AR is not found. I thought the try statement would catch this. A work around for myself would be to use an isset(). But I am confused as to why the try statement does not accept and catch this error.

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

try..catch works on thrown exceptions. Errors are not exceptions. You can silence errors, but please don’t do that. Instead, properly check what you’re getting:

$result = Model()->find('id=1');
if ($result) {
    $id = $result->id;
} else {
    // handle this situation
}

Solution 2

The model needs to be able to throw an exception.

Here’s what your model might look like:

class Model{

   public function find($id){
      $result = //do stuff to find by id

      if (!isset($result)){
          throw new Exception("No result was found for id:$id");
      }
      return $result

   }
}

Then you would use your try/catch block:

try{  

    $id = Model()->find('id=1')->id;

}catch(Exception $e){
    echo 'failed';
}

However, exceptions should only be thrown under “exceptional” circumstances. I don’t think using exceptions to direct program flow is the right way to go about it.

Having said that, if returning a NULL when you attempt to retrieve the ID property is an exceptional situation, then exceptions are certainly suitable.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply