Added error handling and return type checking