Often when I write a functions I want to make sure the inputs to it are valid in order to detect such errors as early as possible (I believe these are called preconditions). When a precondition fails, I've always thrown an exception. But I'm beginning to doubt whether this is the best practice and if not assertions would be more appropriate.

So when should I do which: when is it appropriate to use an assertion and when is it appropriate to throw an exception?

  • 5
    I think this question should be asked on stackoverflow, though it has probably been asked a dozen times there, so you might already find many answers there. – user281377 Oct 29 '10 at 9:05
  • IMHO being language agnostic and theoretical this question is more suitable in this site rather for stackoverflow @user281377 – Sazzad Hissain Khan Dec 31 '19 at 16:03
  • Your question does not make sense to me. Doesn’t your assertion throw an assertion error exception? In my opinion assertions are just a convenience method for checking e.g. preconditions such that the reader can immediately tell that it is not an expected situation. An exception is thrown in any case. – Hartmut Braun Jan 1 at 16:13

Assertions should only be used to verify conditions that should be logically impossible to be false (read: sanity checks). These conditions should only be based on inputs generated by your own code. Any checks based on external inputs should use exceptions.

A simple rule that I tend to follow is verifying private functions' arguments with asserts, and using exceptions for public/protected functions' arguments.

| improve this answer | |
  • Good point about using exceptions for external inputs. I'd also add outputs to that too - problems when trying to create/write to file/database etc. – ChrisF Oct 29 '10 at 10:12
  • 14
    And inevitably you'll find those assertions being triggered in production. +1 for verifying private stuff with asserts! Maybe you could say "use asserts when you are in full control of the inputs"? – Frank Shearar Oct 29 '10 at 10:40
  • 1
    In java, at least, you have to typically enable the assertion check with the -ea command line parameter. This means assertions are effectively no-ops, unless you explicitly turn them on. – Bill Michell Mar 9 '12 at 13:11

Assertions are used to find programming errors. Your programs must work just as well when all assertions are removed.

Exceptions, on the other hand, are for situations that can happen even when the program is perfect; they are caused by external influences, like hardware, network, users etc.

| improve this answer | |
  • This is a pretty good way to put it. If the user inputs something incorrect, throw an exception. If the input is correct but something's still wrong, throw an assert. – Mateen Ulhaq Oct 22 '18 at 21:38
  • If the user inputs something incorrect, that should be expected, not an exception. – gnasher729 Dec 31 '19 at 16:43
  • If it is a good idea to use exceptions for normal control flow is a very controversially discussed topic. – Hartmut Braun Jan 1 at 16:18

Typical programming practice is to compile out assertions from production/release builds. Assertions will help only during internal testing to catch failure of assumptions. You should not assume the behavior of external agencies, so you should not assert on events from the network or user. Also it is a good practice to write handling code for production builds in case an assertion fails.

For example in C,

int printf(const char *fmt, ...)
  assert(fmt);  // may fail in debug build but not in production build
  if (!fmt) return -1; // handle gracefully in production build

Exceptions are meant to be built into production builds. The alternative for exception is returning error and not assertions.

| improve this answer | |
  • 2
    I don't think it's a good idea to put graceful behavior behind an assert for the same condition. Inevitably, because the graceful behavior only exists in the production version, the code that was supposed to deal with the graceful behavior will be poorly tested and crash just as bad as, if not worse than, the code would have were it not guarded. – Sebastian Redl May 3 '13 at 16:37
  • Sebastian Speak for yourself. Most assertions in my code are handled somehow, very few kill the app (and these kill the app in a release build as well). My QA guys don’t like change in behaviour from development to release build. – gnasher729 Dec 31 '19 at 16:45

Although, I have posted the answer in stackoverflow site, that might be still helpful to post here.

Assertions are used,

  1. When you want to stop the program immediately rather to proceed with an unwanted state. This is often related to the philosophy of the Fail-fast [ 1 ] system design.

  2. When there are certain possibilities of cascading failures (i.e. in microservices) for the first unexpected condition that might lead the application into severe inconsistent or unrecoverable states.

  3. When you want to detect bugs in your system exclusively in the debugging period. You might want to disable them in production if language supports.

  4. When you already know that the unexpected conditions arose due to your internal miss-implementation and external system (i.e the callers) has no control over the unwanted state.

Exceptions are used,

  1. When you know that the unexpected conditions arose due to external systems fault (i.e. wrong parameters, lack of resources etc).

  2. When you know that the conditions can be backed up with alternative paths keeping the application functional qualities still intact (i.e. might work well for another call with proper parameters from the caller or external system).

  3. When you want to log and let the developers know about some unwanted state but not a big deal.

Note: “The more you use assertions, the more robust system you get”. In contrast “The more you use exceptions and handle them, the more resilient system you get“.

[ 1 ] Fail fast - In systems design, a fail-fast system is one which immediately reports at its interface any condition that is likely to indicate a failure. Fail-fast systems are usually designed to stop normal operation rather than attempt to continue a possibly flawed process. Such designs often check the system's state at several points in an operation, so any failures can be detected early. The responsibility of a fail-fast module is detecting errors, then letting the next-highest level of the system handle them.

| improve this answer | |

One problem with asserts for me is that they are disabled by default in Java.

We use a fail-first strategy where the program - which may have been running unattended for years - needs to crash as early as possible to avoid data corruption in case of bad data (on an unexpected form). This is what we use the checking for, and by using asserts we basically risk them not being active.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.