9

Problem:

I have the following function which shows a warning No calls to throwing functions occur within 'try' expression

Questions:

  • Why is this warning shown? (The code inside the task throws an error)
  • What should I do to propagate the error to the caller of f1?

Code:

func f1() async throws {
    try await withThrowingTaskGroup(of: Int.self) { group in //No calls to throwing functions occur within 'try' expression
        group.addTask(priority: .high) {
            throw NSError()
        }
    }
}
user1046037
  • 16,755
  • 12
  • 92
  • 138

1 Answers1

9

You indeed have not called any throwing functions, or thrown anything, in the withThrowingTaskGroup closure. You've just added a task for the group to run. This by itself won't throw anything. addTask is not marked throws, though its closure parameter is. It will only throw when you wait for the task's completion in one way or another.

For example:

try await group.waitForAll()

Or if you want to loop through each task of the group:

for try await someInt in group {
    // ...        
}

If you return something in the withThrowingTaskGroup closure, that's what withThrowingTaskGroup will return too. If you throw an error in the closure, withThrowingTaskGroup will throw that error (since it is rethrows), and so will f1.

Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • 1
    Thanks a lot!, just curious wouldn't `withThrowingTaskGroup` wait for all tasks to complete even if `group.waitForAll()` is not invoked? – user1046037 Nov 23 '21 at 13:18
  • 1
    @user1046037 Yes it will, according to the documentation. Normally you would do wait for one or more tasks in the group and get some kind of result for `withThrowingTaskGroup` to return, and this would be a throwing operation. But you are not doing that here, hence the warning. If you are not planning on awaiting any values from the group, then `waitForAll` is just a way to silence the warning. – Sweeper Nov 23 '21 at 13:25
  • 1
    This was also what was required for the underlying errors to be thrown. While I did have `try await withThrowingTaskGroup`, errors in the tasks added were not being propagated until I added this line. Thank you! – Rob S. Jan 01 '23 at 03:40