more robust error handling, replaced a faulty if statement