gpt4 book ai didi

c++ - C++如何像Java Spring Assert一样检查条件并抛出异常

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:50:59 25 4
gpt4 key购买 nike

有没有标准的方法来做这样的事情?

  1. 可用于 Release模式(NDEBUG 定义)
  2. 检查失败时抛出异常。

最好使用标准库或 boost。


为了清楚起见,我在这里使用的“断言”(可能是不同的术语)特别是关于运行时问题,而不是编程问题,例如Spring Assert。在 Java 世界中。

Microsoft.VisualStudio.TestTools.CppUnitTestFramework是很好的候选人,但它是为了测试目的。

最佳答案

在我的一些项目中我使用:

void ASSERT(const bool cond, const std::string& text)
{
if (!cond)
{
throw std::runtime_error(text);
}
}

如果您需要更多信息,您可以使用宏来调用实际函数,如下所示:

void ASSERT(const bool cond, const std::string& text, const std::string& file, const int line)
{
if (!cond)
{
throw std::runtime_error(text + ". In file: " + file + " on line: " + std::to_string(line));
}
}

#define ASSERT(cond, text) ASSERT(cond, text, __FILE__, __LINE__)

示例:

#include <iostream>
#include <string>
#include <stdexcept>

void ASSERT(const bool cond, const std::string& text, const std::string& file, const int line)
{
if (!cond)
{
throw std::runtime_error(text + ". In file: " + file + " on line: " + std::to_string(line));
}
}

#define ASSERT(cond, text) ASSERT(cond, text, __FILE__, __LINE__)

int main()
{
ASSERT(false, "example text");
}

将导致:

terminate called after throwing an instance of 'std::runtime_error'
what(): example text. In file: example.cpp on line: 17
Aborted

更新:

获得与普通 assert 相同的行为,即无条件终止程序,您可以调用 std::abort() (来自 <cstdlib> )而不是使用 throw :

void ASSERT(const bool cond, const std::string& text, const std::string& file, const int line)
{
if (!cond)
{
std::cout << text << ". In file: " << file << " on line: " << line << std::endl;
std::abort();
}
}

#define ASSERT(cond, text) ASSERT(cond, text, __FILE__, __LINE__)

关于c++ - C++如何像Java Spring Assert一样检查条件并抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42712460/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com