Refactor of try-except code and more detailed comments