Added error management to the code