Foreach error handling and finishing scope