Should You Use Assertions?

Should You Use Assertions?

Assertions should be used to check something that should never happen, while an exception should be used to check something that might happen. For example, a function might divide by 0, so an exception should be used, but an assertion could be used to check that the harddrive suddenly disappears.

Are assertions useful?

Programmers can use assertions to help specify programs and to reason about program correctness. ... If an assertion evaluates to false at runtime, an assertion failure results, which typically causes execution to abort.

Why are assertions bad?

Assertions can be used to verify internal implementation invariants, like internal state before or after execution of some method, etc. If assertion fails it really means the logic of the program is broken and you can't recover from this.

Elena Rostova
Author

Elena Rostova

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.