Skip to content

Latest commit

 

History

History
28 lines (20 loc) · 844 Bytes

File metadata and controls

28 lines (20 loc) · 844 Bytes

assert_throw

Asserts that a function throws an exception of the expected type and expected message.

The expected exception type must derive from std::exception. Derived exception types match, like instanceof in JavaScript. Message checks use what() and can be exact string checks or regex checks.

#include <regex>
#include <stdexcept>

#include <kaycxx/assert.hpp>

using namespace kaycxx::assert;

int main() {
    assert_throw<std::runtime_error>(
        [] { throw std::runtime_error{"File not found"}; },
        "File not found"
    );

    assert_throw<std::runtime_error>(
        [] { throw std::runtime_error{"Error 404"}; },
        std::regex{"Error [0-9]+"}
    );
}

The assertion fails when the function does not throw, throws a different exception type, or throws the expected type with the wrong message.