skip to content

In GoogleTest, what exactly does EXPECT_THROW check, and how do you also verify the exception's message?

level: middleimportance: should knowfreq 52%

answer

  1. statement plus exception type
  2. caught by const reference
  3. a base class also passes
  4. the type is checked, not the text

basics

~20 s

EXPECT_THROW(statement, Type) runs the statement and passes if it throws something a catch (Type const&) handler catches, so derived types pass too. It never looks at what(); check the message with ThrowsMessage or a try/catch.

solid answer

~40 s

`EXPECT_THROW(statement, exception_type)` wraps the statement in a `try` with a `catch (exception_type const&)` handler. It passes when that handler catches, so an exception **derived** from the named type passes as well; it fails with "it throws nothing" when nothing is thrown, and with "it throws a different type" when something else is thrown, adding the actual type and `what()` text when the exception derives from `std::exception`. `EXPECT_ANY_THROW` accepts any exception and `EXPECT_NO_THROW` requires none. None of them inspect the message. To check it, use `EXPECT_THAT` with the gMock matcher `ThrowsMessage<E>(HasSubstr("month"))`, or a `try`/`catch` that compares `e.what()` and calls `FAIL()` when nothing is thrown. The macros need exceptions enabled in the build.

code

cpp · 24 lines
cpp
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <cstdio>
#include <stdexcept>

struct Date { int year, month, day; };

Date ParseDate(const char* text) {
  int y = 0, m = 0, d = 0;
  if (std::sscanf(text, "%4d-%2d-%2d", &y, &m, &d) != 3)
    throw std::invalid_argument("not YYYY-MM-DD");
  if (m < 1 || m > 12) throw std::out_of_range("month out of range");
  return {y, m, d};
}

TEST(ParseDateTest, ThrowsOnBadInput) {
  EXPECT_THROW(ParseDate("tomorrow"), std::invalid_argument);
  EXPECT_THROW(ParseDate("2026-13-01"), std::logic_error);  // base: passes
  EXPECT_THROW(ParseDate("2026-13-01"), std::invalid_argument);  // fails
  EXPECT_NO_THROW(ParseDate("2026-10-26"));
  EXPECT_THAT([] { ParseDate("2026-13-01"); },
              testing::ThrowsMessage<std::out_of_range>(
                  testing::HasSubstr("month")));
}

go deeper

for a junior

Recall the three macros, EXPECT_THROW, EXPECT_ANY_THROW and EXPECT_NO_THROW, and that the first takes a statement and a type.

for a middle

Explain the catch-by-const-reference mechanism, why derived types pass, and how to add a message check with ThrowsMessage or try/catch.

for a senior

Spot tests that pass for the wrong reason, a too-general type or an unchecked message, and the comma-in-macro compile failure.

for a principal

Decide which exception types and messages are part of a module's contract and therefore deserve exact assertions in its tests.

## The three exception assertions GoogleTest provides three assertions for code that throws, each in an `EXPECT_` and an `ASSERT_` form: | Assertion | Passes when the statement | |---|---| | `EXPECT_THROW(statement, exception_type)` | throws something a handler for `exception_type` catches | | `EXPECT_ANY_THROW(statement)` | throws anything at all | | `EXPECT_NO_THROW(statement)` | throws nothing | The first argument is a **statement**, not just an expression, so it can be a braced compound statement: `EXPECT_NO_THROW({ Date d = ParseDate(s); Use(d); });`. These macros require exceptions to be enabled in the build; a project compiled with exceptions turned off cannot use them. ## What EXPECT_THROW actually does The macro expands to roughly this shape: 1. Run the statement inside `try { ... }`. 2. `catch (exception_type const&)`: record success. 3. If the named type is not `std::exception` itself, a `catch (const std::exception& e)` handler records a failure that prints the actual dynamic type and `e.what()`. 4. `catch (...)`: record a failure saying "it throws a different type". 5. If nothing was caught, record a failure saying "it throws nothing". Two consequences follow from step 2, which uses ordinary C++ handler matching: - **Derived types pass.** If `ParseDate` throws `std::out_of_range`, then `EXPECT_THROW(ParseDate(s), std::logic_error)` passes, because `std::out_of_range` derives from `std::logic_error`. Name the most specific type you promise to callers. - **Siblings fail.** `std::out_of_range` and `std::invalid_argument` both derive from `std::logic_error` but not from each other, so expecting one when the other is thrown fails, and the output names the real type and its `what()` text. ## The message is not checked `EXPECT_THROW` never reads `what()`. A parser that throws `std::invalid_argument("not YYYY-MM-DD")` for the wrong reason, say an internal bug that happens to throw the same type, still passes. When the message carries the contract, check it explicitly. Two common ways: - **A gMock matcher.** `EXPECT_THAT(callable, ThrowsMessage<std::out_of_range>(HasSubstr("month")))` checks the type and runs a string matcher on `what()`. `Throws<E>()` checks only the type. Matchers come from `gmock/gmock.h`, so the test must link GoogleMock; matchers themselves are taught with the mocking material. - **A hand-written try/catch.** Catch the expected type, compare `e.what()` with `EXPECT_STREQ` or `EXPECT_THAT`, and put `FAIL() << "no exception"` after the call inside the `try`, so a silent return is reported. The hand-written form needs no GoogleMock and reads like this: ```cpp TEST(ParseDateTest, MonthMessage) { try { ParseDate("2026-13-01"); FAIL() << "expected std::out_of_range"; } catch (const std::out_of_range& e) { EXPECT_STREQ(e.what(), "month out of range"); } } ``` `FAIL()` sits inside the `try` so that a call that returns normally is reported. An exception of any other type escapes the `catch` and is reported by the framework as an unexpected exception, which also fails the test. Because `FAIL()` is fatal, this pattern belongs in the test body or another `void` function. ## Pitfalls interviewers like - **Commas in the statement.** Macro arguments are split at commas that are not inside parentheses, and braces do not protect them. `EXPECT_THROW(Make<int, int>(), E)` therefore fails to compile; wrap the statement in parentheses, as in `EXPECT_THROW((Make<int, int>()), E)`, or move it into a helper or lambda. - **Exceptions are not death.** A thrown exception is something a caller could catch, so it is tested with these macros, never with `EXPECT_DEATH`. A death test whose statement throws is reported as a failure. - **An exception escaping the test body.** If an exception escapes a `TEST` without an exception assertion around it, GoogleTest catches it by default and fails the test with a message like `C++ exception with description "disk full" thrown in the test body.` The other tests still run. - **`ASSERT_THROW` versus `EXPECT_THROW`.** The fatal form returns from the current function on failure, exactly like the other `ASSERT_*` macros. ## Which to choose 1. Use `EXPECT_THROW` with the most specific documented type for each invalid input class. 2. Add a message check only when callers depend on the text, such as an error shown to users or parsed by a tool. 3. Use `EXPECT_NO_THROW` sparingly; an unexpected exception already fails the test, so it mainly documents intent or protects a compound statement whose result you then check.

  • Why does EXPECT_THROW(ParseDate(s), std::logic_error) pass when the parser throws std::out_of_range?
    Because the macro catches with an ordinary `catch (std::logic_error const&)` handler, and `std::out_of_range` derives from `std::logic_error`. Any exception a handler for the named type would catch counts as a pass, so the test is only as specific as the type you name.
  • What happens when a statement passed to EXPECT_THROW throws an int?
    The handler for the named type does not match and an `int` is not an `std::exception`, so the `catch (...)` branch records a failure reading "it throws a different type". GoogleTest cannot print a type name or `what()` text for a non-standard exception.

  • EXPECT_THROW checks the exception's what() message as well as its type.
  • EXPECT_THROW requires the exact type, so a derived exception fails.
  • Wrapping the statement in braces protects commas inside the macro argument.
  • A function that may crash on bad input is tested with EXPECT_THROW.
  • An exception escaping a test body crashes the test binary in GoogleTest.