Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it possible to try catch an assert call in a static library(c++)

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.

like image 754
GameHog Avatar asked Aug 07 '16 20:08

GameHog


People also ask

Can you catch assert?

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.

Can you use try-catch in C?

Try-Catch mechanisms are common in many programming languages such as Python, C++, and JavaScript.

Are there exceptions in C?

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.

How do you handle AssertionError in Junit?

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.


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++.

like image 98
nshct Avatar answered Sep 19 '22 00:09

nshct