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

Kat*_*ate 4 c++ exception nlohmann-json

我读了这篇文章并发现处理异常很重要,我使用nlohmann::json(来自github)并且几乎在我的大多数成员函数中都使用nlohmann::json::parse并且nlohmann::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 */
}
Run Code Online (Sandbox Code Playgroud)

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

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 ... */
}
Run Code Online (Sandbox Code Playgroud)

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

ΦXo*_*a ツ 5

我会这样做:设置一个“序列指针”以记录您尝试解析的位置/内容,就像使用带有模式的字符串尝试解析...这样您就可以知道/通知确切位置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 */
    }
}
Run Code Online (Sandbox Code Playgroud)