gpt4 book ai didi

c++ - 有没有更好的方法来处理异常? try-catch block 真的很丑

转载 作者:行者123 更新时间:2023-12-01 14:03:44 25 4
gpt4 key购买 nike

我读了 this并发现处理异常很重要,我使用 nlohmann::json (来自 github )并且几乎在我的大多数成员函数中使用 nlohmann::json::parsenlohmann::json::dump如果输入有问题,就有机会抛出异常。

所以我需要处理那些抛出异常的机会:

bool my_class::function(const std::string& input) const
try
{
using namespace nlohmann;

const auto result = json::parse(input);
const auto name = result["name"].dump();

/* and ... */
}
catch (const std::exception& e)
{
/* handle exception */
}

但我想知道代码的哪一行抛出异常,所以如果我写这样的东西:

bool my_class::function(const std::string& input) const
{
using namespace nlohmann;

try
{
const auto result = json::parse(input);
}
catch(const std::exception& e)
{
/* handle exception */
}

try
{
const auto name = result["name"].dump();
}
catch(const std::exception& e)
{
/* handle exception */
}

/* and ... */
}

它给我留下了数千个 try-catch 块。为什么处理异常更好?

最佳答案

我会这样:
设置一个“序列指针”以记录您要解析的位置/内容,例如使用模式 的字符串正在尝试解析... 这样您就可以知道/通知 json 中错误元素的确切位置。

看看下面的例子,如果“名称有问题,那么 r 持有值”试图解析名称“所以在异常中你有关于什么 json 元素导致问题的信息:)

bool my_class::function(const std::string& input) const
{
std::string r{""};
try
{
using namespace nlohmann;
r="trying to parse input";
const auto result = json::parse(input);

r="trying to parse name";
const auto name = result["name"].dump();

r="trying to parse age";
const auto age = result["age"].dump();

/* and ... */
}
catch (const std::exception& e)
{
/* handle exception */
}
}

关于c++ - 有没有更好的方法来处理异常? try-catch block 真的很丑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62402464/

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