Is it possible to try catch an assert call in c++? Im using the library rapidjson(static library) and its annoying because if it fails to find something in a json file it calls assert. When i want to avoid it calling assert and do the error handling myself.
-
2Asserts shouldn't be used in the case of a "normal" failure. They should only be used when some illegal state has been reached and there isn't any sensible form of recovery that's possible. Perhaps you're misusing rapidjson? This sounds like an [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). – Cornstalks Aug 07 '16 at 20:49
-
See also http://stackoverflow.com/questions/4333371/when-to-use-assert-and-when-to-use-try-catch?rq=1 – melpomene Aug 07 '16 at 20:51
-
You might want to validate your json with a schema first. – Jarod42 Aug 07 '16 at 20:55
-
Ok thanks ill look further in how my code is designed – GameHog Aug 07 '16 at 21:07
-
To @GameHog and everybody else who is frustrated with rapidjson assertions: according to the Author of rapidjson - there is no easy way to replace assert() with a different mechanism. To avoid assertion in rapidjson you have to test/validate the pointer (or key) in your JSON object every possible way before calling a function on it, which means you have to write a lot of extra code. – Pavel Dec 30 '20 at 03:04
1 Answers
You cannot catch an assertion since they have nothing to do with exceptions. The function/macro assert(expr)
is part of C and will cause program termination in an implementation defined manner if the supplied expression evaluates to false
. More detail can be found here.
If you have access to the source of the library in question, recompiling it with the preprocessor macro NDEBUG
defined should disable all assertions. Do note though that this will not replace the assertion with an exception: assert()
will just be replaced by a no operation, no matter to what the supplied expression evaluates.
If you desire exceptions (or any other kind of effective error handling) instead, you will have to modify the library to suit your needs.
Additionally, there is always the possibility of using another library that adheres to modern C++ design practices. For example, this one is suited well if your toolchain supports modern C++.

- 1,197
- 9
- 29