JSON for Modern C++ 3.10.4

◆ exception

template<template< typename U, typename V, typename... Args > class ObjectType = std::map, template< typename U, typename... Args > class ArrayType = std::vector, class StringType = std::string, class BooleanType = bool, class NumberIntegerType = std::int64_t, class NumberUnsignedType = std::uint64_t, class NumberFloatType = double, template< typename U > class AllocatorType = std::allocator, template< typename T, typename SFINAE=void > class JSONSerializer = adl_serializer, class BinaryType = std::vector<std::uint8_t>>
using nlohmann::basic_json< ObjectType, ArrayType, StringType, BooleanType, NumberIntegerType, NumberUnsignedType, NumberFloatType, AllocatorType, JSONSerializer, BinaryType >::exception = detail::exception

This class is an extension of std::exception objects with a member id for exception ids. It is used as the base class for all exceptions thrown by the basic_json class. This class can hence be used as "wildcard" to catch exceptions.

Subclasses:

  • parse_error for exceptions indicating a parse error
  • invalid_iterator for exceptions indicating errors with iterators
  • type_error for exceptions indicating executing a member function with a wrong type
  • out_of_range for exceptions indicating access out of the defined range
  • other_error for exceptions indicating other library errors
Example
The following code shows how arbitrary library exceptions can be caught.
1#include <iostream>
2#include <nlohmann/json.hpp>
3
4using json = nlohmann::json;
5
6int main()
7{
8 try
9 {
10 // calling at() for a non-existing key
11 json j = {{"foo", "bar"}};
12 json k = j.at("non-existing");
13 }
14 catch (json::exception& e)
15 {
16 // output exception information
17 std::cout << "message: " << e.what() << '\n'
18 << "exception id: " << e.id << std::endl;
19 }
20}
detail::exception exception
general exception of the basic_json class
Definition: json.hpp:17763
basic_json<> json
default JSON class
Definition: json.hpp:3472

Output (play with this example online):
message: [json.exception.out_of_range.403] key 'non-existing' not found
exception id: 403
The example code above can be translated with
g++ -std=c++11 -Isingle_include doc/examples/exception.cpp -o exception 
Since
version 3.0.0

Definition at line 17763 of file json.hpp.