Improved type checking and error handling