refactored the code and added a more robust error handling by means of the c++ exceptions