[Typed throws] Implement support for do throws(...) syntax

During the review of SE-0413, typed throws, the notion of a `do throws`
syntax for `do..catch` blocks came up. Implement that syntax and
semantics, as a way to explicitly specify the type of error that is
thrown from the `do` body in `do..catch` statement.
This commit is contained in:
Doug Gregor
2023-12-01 22:29:35 -08:00
parent c7c2f054c8
commit cfe2b3c87d
16 changed files with 206 additions and 26 deletions

View File

@@ -146,3 +146,27 @@ func rethrowsLike<E>(_ body: () throws(E) -> Void) throws(E) { }
func fromRethrows(body: () throws -> Void) rethrows {
try rethrowsLike(body) // expected-error{{call can throw, but the error is not handled; a function declared 'rethrows' may only throw if its parameter does}}
}
// Explicit specification of the thrown type within a `do..catch` block.
func testDoCatchExplicitTyped() {
do throws {
try doHomework() // would normally infer HomeworkError
} catch {
let _: Int = error // expected-error{{cannot convert value of type 'any Error' to specified type 'Int'}}
}
do throws(any Error) {
try doHomework() // would normally infer HomeworkError
} catch {
let _: Int = error // expected-error{{cannot convert value of type 'any Error' to specified type 'Int'}}
}
do throws(HomeworkError) {
throw .forgot // okay, HomeworkError.forgot based on context
} catch {
let _: Int = error // expected-error{{cannot convert value of type 'HomeworkError' to specified type 'Int'}}
}
do throws(HomeworkError) { // expected-error{{a 'do' statement with a 'throws' clause must have at least one 'catch'}}
}
}