In Catch2, how do REQUIRE_THROWS_AS, REQUIRE_THROWS_WITH and REQUIRE_THROWS_MATCHES differ when testing that a degenerate triangle throws?
answer
- type, message, or both
- the type gets const& added
- a base class also matches
- a plain string must match exactly
basics
~20 sREQUIRE_THROWS_AS checks the exception's type, accepting derived types. REQUIRE_THROWS_WITH checks its message as a string, exactly or through a string matcher. REQUIRE_THROWS_MATCHES checks the type and then applies a matcher, such as Message, to the caught exception.
solid answer
~40 sAll three take a single expression and fail if it does not throw. `REQUIRE_THROWS_AS(expr, T)` passes if the exception can be caught as `T const&`, so a `std::invalid_argument` passes for `std::invalid_argument` and for its base `std::logic_error`, while an unrelated type is reported as an unexpected exception; write `T` without `const&`, which Catch2 adds. `REQUIRE_THROWS_WITH(expr, s)` converts the exception to a string, its `what()` for a `std::exception`, and compares it **exactly** with a string, or applies a string matcher such as `ContainsSubstring("degenerate")`. `REQUIRE_THROWS_MATCHES(expr, T, matcher)` catches as `T` and applies a matcher to the exception object, for example `Message("degenerate triangle")` or a `Predicate` on a custom field. `REQUIRE_THROWS` accepts any exception, and `REQUIRE_NOTHROW` asserts none.
code
cpp · 26 lines#include <catch2/catch_test_macros.hpp>
#include <catch2/matchers/catch_matchers_exception.hpp>
#include <catch2/matchers/catch_matchers_string.hpp>
#include <cmath>
#include <stdexcept>
struct Point { double x, y; };
double triangleArea(Point a, Point b, Point c) {
double twice = (b.x - a.x) * (c.y - a.y) - (c.x - a.x) * (b.y - a.y);
if (twice == 0.0) throw std::invalid_argument("degenerate triangle");
return std::fabs(twice) / 2.0;
}
using Catch::Matchers::ContainsSubstring;
using Catch::Matchers::Message;
TEST_CASE("degenerate triangles throw", "[geometry]") {
Point a{0, 0}, b{1, 1}, c{2, 2}; // collinear
CHECK_THROWS_AS(triangleArea(a, b, c), std::invalid_argument);
CHECK_THROWS_AS(triangleArea(a, b, c), std::logic_error); // base: passes
CHECK_THROWS_WITH(triangleArea(a, b, c), "degenerate triangle");
CHECK_THROWS_WITH(triangleArea(a, b, c), ContainsSubstring("degenerate"));
CHECK_THROWS_MATCHES(triangleArea(a, b, c), std::invalid_argument,
Message("degenerate triangle"));
CHECK_NOTHROW(triangleArea(a, b, {0, 1}));
}go deeper
Recall that THROWS_AS checks the type, THROWS_WITH checks the message, and that both fail if nothing is thrown.
Explain that THROWS_AS catches by const reference so base classes match, that a plain string in THROWS_WITH is an exact comparison, and when to reach for a string matcher.
Choose the assertion that pins the actual contract: the most specific documented type, message checks only where text is part of the interface, and THROWS_MATCHES for structured error data.
Treat exception types and messages as part of a component's interface, and decide which of them tests may pin so that rewording an error does not break unrelated suites.
## The exception assertion family Catch2 has a group of assertions for code that should or should not throw. Each has a `REQUIRE_` form that aborts the current run on failure and a `CHECK_` form that continues. | Assertion | Passes when | |---|---| | `REQUIRE_NOTHROW(expr)` | evaluating `expr` throws nothing | | `REQUIRE_THROWS(expr)` | `expr` throws anything | | `REQUIRE_THROWS_AS(expr, T)` | `expr` throws something catchable as `T const&` | | `REQUIRE_THROWS_WITH(expr, s)` | the exception, converted to a string, equals `s` or matches a string matcher | | `REQUIRE_THROWS_MATCHES(expr, T, m)` | the exception is catchable as `T` and matcher `m` accepts it | `REQUIRE_THROWS_MATCHES` is declared in `catch2/matchers/catch_matchers.hpp`, the `Message` and `MessageMatches` matchers in `catch2/matchers/catch_matchers_exception.hpp`, and string matchers such as `ContainsSubstring` in `catch2/matchers/catch_matchers_string.hpp`. ## Testing a degenerate triangle An area function that throws `std::invalid_argument("degenerate triangle")` for collinear points was checked with each form. Against Catch2 3.16.1: - `CHECK_THROWS_AS(triangleArea(a, b, c), std::invalid_argument)` passed. - `CHECK_THROWS_AS(..., std::logic_error)` also passed, because `std::invalid_argument` derives from `std::logic_error`. - `CHECK_THROWS_AS(..., std::runtime_error)` failed with `due to unexpected exception with message: degenerate triangle`. - `CHECK_THROWS_WITH(..., "degenerate triangle")` passed. - `CHECK_THROWS_WITH(..., "degenerate")` failed with the expansion `"degenerate triangle" equals: "degenerate"`. - `CHECK_THROWS_WITH(..., ContainsSubstring("degenerate"))` passed. - `CHECK_THROWS_MATCHES(..., std::invalid_argument, Message("degenerate triangle"))` passed. When the expression does not throw at all, the report says `because no exception was thrown where one was expected`. ## THROWS_AS: the type, by catch rules The macro catches with an ordinary handler for `T const&`. The documentation states that the type is extended with `const&` and you should not add it yourself. Because a handler for a base class catches derived exceptions, `THROWS_AS` is a "this type or a subclass" check, not an exact-type check. Two practical rules follow: 1. Name the **most specific** type the contract promises, otherwise a base-class assertion lets a wrong subclass through. 2. Name a type the function actually documents; asserting `std::exception` proves little beyond "something was thrown". ## THROWS_WITH: the message The exception is converted to a string, which for a type derived from `std::exception` is the result of `what()`, and compared with the second argument. - A plain string literal means **exact equality**. - A string matcher gives partial checks: `ContainsSubstring`, `StartsWith`, `EndsWith`, `Equals` and the regex matcher `Matches`, each optionally case-insensitive, and combinable with `&&` and `||`. Message assertions are brittle by nature: rewording an error message breaks them. Use them where the message is part of the contract, such as text shown to a user or parsed by a tool, and prefer a substring when only a key phrase matters. ## THROWS_MATCHES: type plus anything you can express `REQUIRE_THROWS_MATCHES(expr, T, matcher)` first requires the exception to be catchable as `T`, then calls the matcher on the caught object. That allows checks on custom members, not just the message, for example with the `Predicate` matcher from `catch2/matchers/catch_matchers_predicate.hpp`: ```cpp REQUIRE_THROWS_MATCHES(parse(text), parse_error, Predicate<parse_error>([](parse_error const& e) { return e.line() == 3; }, "error reported on line 3")); ``` `Message(s)` compares `what()` exactly; `MessageMatches(m)`, added in Catch2 3.3.0, applies a string matcher to it. ## One expression, and commas The `THROWS` family takes a **single expression**, not a sequence of statements. For a multi-step operation, wrap it in an immediately invoked lambda. A comma inside the expression, as in a `std::pair<int, int>` construction, splits the macro arguments; a type alias or extra parentheses fixes that. ## Common mistakes in review 1. **A base class in `THROWS_AS`.** `std::exception` or `std::logic_error` passes for many unrelated failures; name the type the function documents. 2. **A plain string meant as a substring.** `REQUIRE_THROWS_WITH(f(), "degenerate")` is an equality check and fails against a longer message. 3. **Statements instead of an expression.** Put a multi-step setup in an immediately invoked lambda, or perform the setup before the assertion and keep only the throwing call inside it. 4. **Setup that throws first.** If constructing the inputs throws the expected type, the assertion passes without ever reaching the code under test; build the inputs outside the assertion. 5. **`CHECK_THROWS_AS` followed by code that assumes success.** The continuing form does not stop the run, so later lines must not depend on the throw having happened. ## Choosing the form - Type is the contract: `THROWS_AS`. - Message is the contract: `THROWS_WITH`, with a matcher unless the full text is guaranteed. - Type and a property: `THROWS_MATCHES`. - Any failure will do: `THROWS`, but say why in a comment, because it also passes on a bug that throws something else.
- How do you check in Catch2 that a sequence of several statements throws?The `THROWS` assertions take a single expression, so wrap the statements in a lambda and call it immediately: `REQUIRE_THROWS_AS([&] { Point c = mirror(b); triangleArea(a, b, c); }(), std::invalid_argument);`, where `mirror` stands for whatever setup the test needs. The lambda call is one expression, and any exception escaping from its body is what the assertion examines.
- Why can a Catch2 REQUIRE_THROWS assertion pass even though the code under test has a bug?`REQUIRE_THROWS` accepts an exception of any type, so a `std::out_of_range` from an indexing bug satisfies it just as well as the intended `std::invalid_argument`. Asserting the specific type with `REQUIRE_THROWS_AS`, or the type plus a message matcher with `REQUIRE_THROWS_MATCHES`, makes the test fail for the wrong exception.
- REQUIRE_THROWS_AS only passes for the exact type, never a derived one.
- You should write REQUIRE_THROWS_AS(expr, const std::invalid_argument&).
- REQUIRE_THROWS_WITH with a plain string checks that the message contains it.
- REQUIRE_THROWS is as strong a check as REQUIRE_THROWS_AS.
- The THROWS assertions accept a block of several statements.