1# JSON_CATCH_USER, JSON_THROW_USER, JSON_TRY_USER 2 3```cpp 4// (1) 5#define JSON_CATCH_USER(exception) /* value */ 6// (2) 7#define JSON_THROW_USER(exception) /* value */ 8// (3) 9#define JSON_TRY_USER /* value */ 10``` 11 12Controls how exceptions are handled by the library. 13 141. This macro overrides [`#!cpp catch`](https://en.cppreference.com/w/cpp/language/try_catch) calls inside the library. 15 The argument is the type of the exception to catch. As of version 3.8.0, the library only catches `std::out_of_range` 16 exceptions internally to rethrow them as [`json::out_of_range`](../../home/exceptions.md#out-of-range) exceptions. 17 The macro is always followed by a scope. 182. This macro overrides `#!cpp throw` calls inside the library. The argument is the exception to be thrown. Note that 19 `JSON_THROW_USER` should leave the current scope (e.g., by throwing or aborting), as continuing after it may yield 20 undefined behavior. 213. This macro overrides `#!cpp try` calls inside the library. It has no arguments and is always followed by a scope. 22 23## Parameters 24 25`exception` (in) 26: an exception type 27 28## Default definition 29 30By default, the macros map to their respective C++ keywords: 31 32```cpp 33#define JSON_CATCH_USER(exception) catch(exception) 34#define JSON_THROW_USER(exception) throw exception 35#define JSON_TRY_USER try 36``` 37 38When exceptions are switched off, the `#!cpp try` block is executed unconditionally, and throwing exceptions is 39replaced by calling [`std::abort`](https://en.cppreference.com/w/cpp/utility/program/abort) to make reaching the 40`#!cpp throw` branch abort the process. 41 42```cpp 43#define JSON_THROW_USER(exception) std::abort() 44#define JSON_TRY_USER if (true) 45#define JSON_CATCH_USER(exception) if (false) 46``` 47 48## Examples 49 50??? example 51 52 The code below switches off exceptions and creates a log entry with a detailed error message in case of errors. 53 54 ```cpp 55 #include <iostream> 56 57 #define JSON_TRY_USER if(true) 58 #define JSON_CATCH_USER(exception) if(false) 59 #define JSON_THROW_USER(exception) \ 60 {std::clog << "Error in " << __FILE__ << ":" << __LINE__ \ 61 << " (function " << __FUNCTION__ << ") - " \ 62 << (exception).what() << std::endl; \ 63 std::abort();} 64 65 #include <nlohmann/json.hpp> 66 ``` 67 68## See also 69 70- [Switch off exceptions](../../home/exceptions.md#switch-off-exceptions) for more information how to switch off exceptions 71- [JSON_NOEXCEPTION](JSON_NOEXCEPTION) - switch off exceptions 72 73## Version history 74 75- Added in version 3.1.0. 76