Replace exception throwing by flag passing in recursive calls