add exceptions and try to avoid memory leaks