Add a try-catch block and other fixes