replace try-catch-block and add check in closing output.