Updated for possible NPEs and better stack trace output.