adding Exceptions and optimized code