Refactoring codes, implementing try catch statements