Expanded code to include error handling at each level.