added some checks and a try catch