Better error handling to avoid memory leaks.