Better error handling and memory managment