some corrections to the previous code, mainly handling Exception better