Assertions Or Exceptions?
Programming languages such as C++, Java or C# provide both assertions and exceptions which somehow serve the same purpose: enable you to build better programs.
However, it seems it’s not quite clear to programmers when to use assertions or exceptions in their own code.
While assertions and exceptions both signal an expression is not true while it should, the first notable difference is that assertions are not always enabled:
- in C, C++, Objective-C or C#, they are compiled out of release builds
- in Java, they are compiled in but disabled by default and can be enabled at various granularities with the ‑enableassertions flag
- other languages have their own rules
Although their behaviour seems to be quite similar, particularly in Java or C# where they ultimately throw an exception when the expression is
false, the respective intended usage of assertions and exceptions is very different:
- use exceptions when checking parameters passed to
protectedmethods and constructors
- use exceptions to provide feedback to the user or when you expect the client code can reasonably recover from an exceptional situation (e.g. a missing file)
use exceptions to address problems that might occur
- use assertions when checking pre-conditions, post-conditions and invariants of private/internal code
- use assertions to provide feedback to yourself or the team
- use assertions when checking for impossible situations otherwise it means there is a serious flaw in the program (e.g. an index out of bounds)
- use assertions to state things that (supposedly) can’t happen
In other words, exceptions address the robustness of your application while assertions address its correctness.
Also, assertions are an investment over time: they ensure what you think must be true remains true throughout the life of your codebase. Assert often. Assert different parts of some complex code remain consistent. This will save you precious time in future debugging sessions.
This article is based on a Stack Overflow answer I wrote a while ago.