General Tips

Assertions vs. Error handling

Many programmers are not sure or not aware when to use assertions and when to use conditions-checking and error handling code. Here’s a tip on this.

But first, what is an assertion? An assertion is a line in your code which looks like this:


When execution reaches this point, if the condition is true, then the program continues with the next operator. However, if the condition is false, then the execution flow is terminated, and an error is reported to the debugger or to the command shell.

Important: the assertions are intended to use for debugging, and usually have an easy method of exculding them from the release version (e.g. #define NDEBUG for the assertion from the C standard library).

By their definition and implementation, assertions are targeted at catching the possible mistakes of the DEVELOPER (of the application or of the library code), at the situations “this variable should NEVER be negative (at this place of the code)”. Use the assertions to check conditions in the code when the user performs everything correctly, but your application does not give the intended result (and that is essentially the definition of debugging).

However, when the condition you are trying to avoid CAN arise during the normal execution because of the USER mistakes (e.g. you ask for an integer number but user inputs a text or a floating-point number), you need to implement the proper error handling (set of if/else operators, plus reporting wrond data with the help of error codes or exceptions, plus reporting back to the user with the help of console outputs or message boxes).

Sometimes, for the production code you need to combine both. Assertions check the conditions during the development and testing (and force to notice and correct the errors immediately). For the release version assertions are removed, and the error hanling code makes sure that the program will not not crash if things do go wrong during the execution.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s