nlohmann / json

JSON for Modern C++
https://json.nlohmann.me
MIT License
42.01k stars 6.63k forks source link

try/catch block doesn't work while accessing const json& array. #3998

Closed itamarcps closed 1 year ago

itamarcps commented 1 year ago

Description

try/catch block with a function taking const json& as a argument and accessing an array within the json doesn't catch.

Reproduction steps

Reproducible with the code included in this issue.

Expected vs. actual results

The function should be able to catch, if you take out the const from the argument, it catches successfully.

Minimal code example

#include <iostream>
#include "json.hpp"

using json = nlohmann::ordered_json;

void function(const json& request) {
  try {
    std::cout << "Trying to get" << std::endl;
    std::cout << request.dump() << std::endl;
    const auto value = request["information"][0].get<std::string>();
    std::cout << "Got" << std::endl;
  } catch(std::exception &e) {
    std::cout << "Caught Exception" << std::endl;
    throw std::runtime_error("Error");
  }
}

int main() {
  json request;
  request["information"] = json::array();
  try {
    function(request);
  } catch (std::exception &e) {
    std::cout << "Catched!" << std::endl;
    std::cout << e.what() << std::endl;
  }
 return 0;
}

Error messages

The function segfaults instead of throwing.

Compiler and operating system

gcc 10.2.1

Library version

C++20, Latest nlohmann/json release.

Validation

gregmarr commented 1 year ago

It is undefined behavior to use operator[] on a const object for an array index that doesn't exist. You need to be sure that it exists first. If you want checked access, you need to use at() instead. https://json.nlohmann.me/api/basic_json/operator%5B%5D/#notes

itamarcps commented 1 year ago

Thanks, using .at(idx) works perfectly fine for me.