Updated code to handle exceptions