<!--
{
  "availability" : [
    "Swift: 6.0.0 -",
    "Xcode: 16.0.0 -",
    "iOS: -",
    "iPadOS: -",
    "macCatalyst: -",
    "macOS: -",
    "swift: 6.0.0 -",
    "tvOS: -",
    "visionOS: -",
    "watchOS: -"
  ],
  "documentType" : "symbol",
  "framework" : "Testing",
  "identifier" : "/documentation/Testing/expect(_:sourceLocation:performing:throws:)",
  "metadataVersion" : "0.1.0",
  "role" : "Macro",
  "symbol" : {
    "kind" : "Macro",
    "modules" : [
      "Swift Testing"
    ],
    "preciseIdentifier" : "s:7Testing6expect_14sourceLocation10performing6throwss5Error_pSgAA7CommentVSgyXK_AA06SourceD0VxyYaKXESbsAF_pYaKXEtclufm"
  },
  "title" : "expect(_:sourceLocation:performing:throws:)"
}
-->

# expect(_:sourceLocation:performing:throws:)

Check that an expression always throws an error matching some condition.

```
@discardableResult @freestanding(expression) macro expect<R>(_ comment: @autoclosure () -> Comment? = nil, sourceLocation: SourceLocation = #_sourceLocation, performing expression: () async throws -> R, throws errorMatcher: (any Error) async throws -> Bool) -> (any Error)?
```

## Parameters

`comment`

A comment describing the expectation.

`sourceLocation`

The source location to which recorded expectations and
issues should be attributed.

`expression`

The expression to be evaluated.

`errorMatcher`

A closure to invoke when `expression` throws an error that
indicates if it matched or not.

## Return Value

If the expectation passes, the error that was thrown by
`expression`. If the expectation fails, the result is `nil`.

## Overview

Use this overload of `#expect()` when the expression `expression` *should*
throw an error, but the logic to determine if the error matches is complex:

```swift
#expect {
  FoodTruck.shared.engine.batteryLevel = 0
  try FoodTruck.shared.engine.start()
} throws: { error in
  return error == EngineFailureError.batteryDied
    || error == EngineFailureError.stillCharging
}
```

If `expression` does not throw an error, if it throws an error that is
not matched by `errorMatcher`, or if `errorMatcher` throws an error
(including the error passed to it), an [`Issue`](/documentation/Testing/Issue) is recorded for the test
that is running in the current task. Any value returned by `expression` is
discarded.

If the thrown error need only be an instance of a particular type, use
[`expect(throws:_:sourceLocation:performing:)`](/documentation/Testing/expect(throws:_:sourceLocation:performing:)-1hfms) instead. If the thrown
error need only equal another instance of [`Error`](https://developer.apple.com/documentation/swift/error),
use [`expect(throws:_:sourceLocation:performing:)`](/documentation/Testing/expect(throws:_:sourceLocation:performing:)-7du1h) instead.

---

Copyright &copy; 2026 Apple Inc. All rights reserved. | [Terms of Use](https://www.apple.com/legal/internet-services/terms/site.html) | [Privacy Policy](https://www.apple.com/privacy/privacy-policy)