Refactored if-block with try-catch blocks