Back to questions
JuniorTheoryCommon
What does the program print (lines separated by spaces)?
enum TextError: Error { case empty }
func letters(in text: String) throws -> Int {
if text.isEmpty { throw TextError.empty }
return text.count
}
do {
print(try letters(in: "ab"))
print(try letters(in: ""))
print("end")
} catch {
print("error")
}2 error
- Expecting
2 error end: thinking thedoblock goes on aftercatch. An error skips the rest ofdofor good, and aftercatchthe program continues below it. - Expecting
erroralone: thinking adoblock runs only when none of its lines throws. Its lines run in order, so2is printed before the error.
- What would the program print if
print("end")stood after the closing brace ofcatch? - How would you change the second call so that empty text gives
0instead of reachingcatch?