未捕获 Simdjson 库的 C++ 异常
c++ exception not caught for simdjson library
我正在尝试使用 simdjson 库:https://github.com/simdjson/simdjson#documentation
但是,我需要解析的 json 来自 websocket 连接,并不总是包含相同的键。因此,有时尝试从解析的 json 对象中按键提取值会引发异常:
terminate called after throwing an instance of 'simdjson::simdjson_error'
what(): The JSON field referenced does not exist in this object.
Aborted (core dumped)
下面尝试使异常处理正常工作的示例代码:
#include <iostream>
#include <string>
#include <chrono>
#include "simdjson.h"
using namespace std;
using namespace simdjson;
int main() {
auto cars_json = R"( [
{ "make": "Toyota", "model": "Camry", "year": 2018, "tire_pressure": [ 40.1, 39.9, 37.7, 40.4 ] },
{ "make": "Kia", "model": "Soul", "year": 2012, "tire_pressure": [ 30.1, 31.0, 28.6, 28.7 ] },
{ "make": "Toyota", "model": "Tercel", "year": 1999, "tire_pressure": [ 29.8, 30.0, 30.2, 30.5 ] }
] )"_padded;
simdjson::error_code error_c;
dom::parser parser;
dom::object doc;
dom::element elem;
const char* value;
doc = parser.parse(cars_json);
try
{
doc["clOrdID"].get<const char*>().tie(value, error_c);
}
catch (simdjson_error e)
{
cout << 1 << endl;
}
return 0;
}
我已经阅读了有关库错误处理的文档: https://github.com/simdjson/simdjson/blob/master/doc/basics.md#error-handling
但是,使用 try-catch 块和上述文档中描述的错误处理方法仍会导致程序退出。我对 c++ 编程非常陌生,因此也是该语言中的异常处理 - 有关如何从此库中捕获任何异常的任何指导将不胜感激!
首先,您应该将parser.parse(cars_json);
移动到try / catch
块中,以便捕获解析器异常
try {
doc = parser.parse(cars_json);
} catch (simdjson::simdjson_error e) {
cout << e.what() << endl;
}
然后您可能会意识到parser
不会返回simdjson::dom::object
而是返回simdjson::dom::array
。
下面是转换为const char*
的更新示例
const char* value;
try {
auto root = parser.parse(cars_json);
cout << "root: " << root.type() << endl;
auto car = root.at(0);
if(car["make"].is_string()){
cout << "first car: " << car["make"] << endl;
}
//check non-existing element
if(car["foo"].is_string()){
// exception won't be thrown
}
std::string_view sv = root.at(1)["model"];
cout << "string view: " << sv << endl;
//conversion to const char*
value = std::string(sv).c_str();
cout << "const char: " << value << endl;
} catch (const simdjson::simdjson_error &e) {
cout << e.what() << endl;
}
输出应为:
root: array
first car: "Toyota"
string view: Soul
const char: Soul
这是一个老问题,但我在使用发布v0.9.6
时遇到了同样的问题(来自文档推荐的 CMake 安装(
唯一的其他答案永远不会真正使代码工作。
我升级到v3.1.6
,这是撰写此答案时的最新内容,然后删除了我的CMake文件夹,并且此错误已修复。
相关文章:
- 处理多个异常集合的C++方法
- 我在c++代码中生成了一个运行时#3异常
- 孤立代码块在结构中引发异常
- C++中的赋值发生,尽管右侧出现异常
- 从构造函数抛出异常时如何克服内存泄漏
- 异常属于C++中的线程还是进程
- 当类定义不可见时捕获异常
- 引发异常:读取访问冲突**dynamicArray**为0x1118235.发生
- 为什么异常不退出程序?
- 为什么我应该在异常处理中使用std::cerr而不是std::cout
- 如何修复链表类实现的未处理异常0xDDDDDDDD
- 关于:C++中异常对象的范围:为什么我没有得到副本?
- 是什么导致了Unity 3D中的"错误线程异常"?
- 如何将strftime中的格式错误作为异常捕获
- 创建具有 new in 函数和"this is nullptr"异常的对象
- 尝试使用智能指针时引发异常
- 函数如何通知用户它基于函数原型抛出异常?
- 是否值得降低我的代码的可读性,以便在出现内存不足错误时提供异常安全性?
- 当我使用 C++ 中的 C# dll 来使用 Selenium 时,存在异常处理问题
- Pytorch torch.cholesky忽略异常