Further to Pradeep Nayak's reply, the ultimate cause of the problems I was having were missing foreign key constraints on the civicrm_relationship table leaving orphaned data when contacts were deleted.
Therefore, a solution which fixes the problem rather than working around it would be:
Check that all foreign key constraints are missing on ...
Your system have orphan data in civicrm_relationship table. There are few rows in civicrm_relationship table that have contact id in column civicrm_relationship.contact_id_a or civicrm_relationship_contact_id_b are missing in civicrm_contact.
FROM civicrm_relationship cr
LEFT JOIN civicrm_contact cc
ON cc.id = cr.contact_id_a
WHERE cc.id IS ...
If you getting the error: Uncaught PHP Exception Unable to write to the .../files/civicrm/templates_c" directory.
You have probably used drush cache clear run under your account and that created the temp files owned by the user running drush.
SO you can "run drush as the web server user"
sudo -u apache drush cr
or you can just look at the ...