Added exception handling (and minor reformatting)