Search code examples
c++exceptionnlohmann-json

Is there a better way to handle exceptions ? try-catch block is really ugly


I read this and find out it's important to handle exceptions, i use nlohmann::json (from github) and nearly in most of my member functions is use nlohmann::json::parse and nlohmann::json::dump which make a chance to throw exceptions if the input has a problem.

So I need to handle those chance of throwing exception something like this:

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 */
}

But i want to know which line of the code throw exception, so if i write something like this:

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 ... */
}

It left me with thousands of try-catch blocks. It's a better why to handle exception ?


Solution

  • I would go like this: set a "sequence pointer" to keep the record of where/what are you trying to parse, like with a string with the pattern trying to parse a... so you can know/notify where exactly was the faulty element in the json.

    look in the example below, if "name is faulty, then r is holding the value "trying to parse name" so in the exception you have the information about what json element is causing the problem :)

    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 */
        }
    }