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.
In order to catch the assertion error, we need to declare the assertion statement in the try block with the second expression being the message to be displayed and catch the assertion error in the catch block.
Try-Catch mechanisms are common in many programming languages such as Python, C++, and JavaScript.
The C programming language does not support exception handling nor error handling. It is an additional feature offered by C. In spite of the absence of this feature, there are certain ways to implement error handling in C. Generally, in case of an error, most of the functions either return a null value or -1.
In order to handle the assertion error, we need to declare the assertion statement in the try block and catch the assertion error in the catch block.
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++.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With