Added error handling for factory methods.