Add a null reference check and improve error messages