Replace for with foreach
Print stack trace on exception.