Add a null reference check and improve error messages



<!---
@huboard:{"order":4.25,"milestone_order":18,"custom_state":""}
-->