improved error handling and added null check