Refined the error handling; overall the resulting code is cleaner