75

I never got the idea of asserts -- why should you ever use them?

I mean, let's say I were a formula driver and all the asserts were things like security belt, helmet, etc.

The tests (in debug) were all okay, but now we want to do racing (release)! Should we drop all security, because there were no issues while testing?

I will never ever remove them. I think most of the guys that claim that removing something comparable to asserts never profiled their code or the asserts were absolute displaced. I've never seen any real performance advantage especially regarding the 80 / 20 rule.

So, am I missing the point somehow, or could anybody tell me, why I should use asserts? By the way, I'm using unit tests.

Sam
  • 7,252
  • 16
  • 46
  • 65
  • You never got the idea, and yet you will never ever remove them? Seems like you agree and disagree at the same time. – rtn Jul 04 '09 at 09:42
  • 2
    Assertions are only used by lazy programmers who don't want to code up error handling. If you know an error is possible, handle it. If it's not possible, then there is no reason to assert. – Justin Aug 07 '09 at 17:09
  • 22
    Justin, that is not what asserts are for. Asserts are for blowing up hard when something that literally should never happen (because it indicates a programming error) happens. They're not for handling everyday, predictable error conditions. – Mike Daniels Aug 07 '09 at 17:17

19 Answers19

82

First, the performance difference can be huge. In one project our asserts literally caused a 3x slowdown. But they helped us uncover some really pesky bugs.

Which is exactly the point.

Asserts are there to help you catch bugs. And because they are removed in release builds, we can afford to put a lot of them in without worrying about performance. If you're not there to actually act on any failed assertions, they become worthless, so we might as well remove them.

Even catching the error and throwing an exception isn't really a solution. The program logic is flawed, and even if we handle the exception, the program is still broken.

What asserts basically boil down to is "Why bother catching errors you can't handle?"

Some errors must be caught during development. If they slip past testing and into the release build used by a customer, the program is just broken, and no amount of runtime error-checking is going to fix it.

I never got the idea of asserts -- why should you ever use them?

I mean, let's say I were a formula driver and all the asserts were things like security belt, helmet, etc.

Yes, that's a good example of when not to use an assert. These are things that might actually go wrong at runtime, and which need to be checked. Your formula one driver might forget some security precaution, and if he does, we want to halt the whole thing before anyone gets hurt.

But what about the check to see that the engine is installed? Do we need to check that during the race?

Of course not. If we get into the race without an engine, we're screwed, and even if we detect the error, it's too late to do anything about it.

Instead, this is an error that must be caught during development or not at all. If the designers forget to put an engine in their car, they need to detect this error during development. That's an assert. It's relevant to the developers during development, but afterwards, the error must not exist, and if it does, there's nothing we can do.

That's basically the difference. An exception is there to help the user, by handling errors that can be handled.

An assert is there to help you, by alerting you to errors that must never occur in the first place, that must be fixed before the product can be shipped. Errors that do not depend on user input, but on your code doing what it is supposed to do.

The square root of four must never evaluate to three. The error is simply impossible. If it does occur, your program logic is just broken. It doesn't matter how much error handling we wrap around it, it's something that must be caught during development or not at all. If we used exception handling to check for this error and handle it, what is the exception going to do? Tell the user "the program is fundamentally broken. Don't ever use it"?

An email from the developer could have achieved that. Why bother building it into the program code? That's an example of a problem that simply must not occur. If it does, we have to go back and fix the program. No other form of error handling is possible.

But some errors, like being unable to open a file for reading, are possible. Even though it might be a bad thing if it happens, we have to accept that it can happen. So we need to handle it if it does.

Asserts are for catching the errors that can't possibly happen.

Community
  • 1
  • 1
jalf
  • 243,077
  • 51
  • 345
  • 550
  • 1
    I think that many posts here are true, but this one is really close to my phylosophy. Asserts help me while developing, while constructing my application. I prefere it to stop and generate a crash dump once an error occured that I do not expect while doing my development .. race :-) . +1 ! – yves Baumes Aug 07 '09 at 17:26
  • That's probably what does formula one team when developping new engine (for instance). They put their engine at test on a circuit with many sensor and other stuffs. When people in the pit detects errors, they ask the driver to stop at the pit to do some correction, etc, etc, etc. Up the time they reach their goal: an engine that is ready for .. production. :-) – yves Baumes Aug 07 '09 at 17:30
  • "If we get into the race without an engine, we're screwed" But how about "we got into the race without the brake"? The car still starts OK, but the driver would be screwed _in the middle of the race_, if nobody cared to check it during the start of the race. In that case, if we detect the error, it is _not_ too late to do anything about it -- we can abort the thing and not endanger the driver's life. Strictly speaking -- if something bypassed the assertion (in production), the program could do anything including deleting sensitive files. – kizzx2 Dec 05 '10 at 13:52
  • @kizzx2: "before the race" is analogous to *during testing/compilation*, which is where asserts are handy. *during the race* corresponds to *at run-time*. So I don't really see how this contradicts anything I said. The car *must not* enter the race without brakes. Such an error has to be caught *before* the car is started. Just like certain errors in software have to be caught *before* the program is launched: during compilation/testing, for example via an assert. If you do get into the race with no brakes, signalling an error doesn't really help. It's too late to handle the problem safely. – jalf Dec 05 '10 at 15:37
  • 1
    My apologies -- analogies only go so far. I think my points can be summed up as: 1) We never know what's impossible -- if we knew, no software would crash. What we thought as _impossible_ (assertions) might as well happen in production. 2) When an failed assertion goes unstopped -- the program has entered undefined behavior. I find it irresponsible to let the program continue without _any_ sort of error handling. ------- Of course it's not absolute truth. Some programs (mission critical) require more rigorous safety checks and for some, "the show must go on" (e.g. video games) – kizzx2 Dec 05 '10 at 23:48
  • @kizzx2: it doesn't matter what we "know" is impossible though. What matters is that there are things that are impossible to *handle*. There are errors that, if they occur, mean that something is so fundamentally wrong with the application that we have no way to deal with it. The *only* sane response is to catch it during development and *fix* it. If it happens "in the wild", there is just nothing we can do. Sure, we can catch exceptions until the cows come home, and then what? What do we do with them? How do we recover? We can't, because things have gone so wrong that we can't trust our code. – jalf Dec 06 '10 at 02:21
  • Assertions are a debugging aid for the programmer to make sure that such situations do not arise. But *if* they do, then we're deep into undefined behavior *even if we try to handle it*. – jalf Dec 06 '10 at 02:22
  • say your code contains a vector math library. In your normalization function, you might well define an assert verifying that the resulting vector *does* have length 1 as expected. But what "error handling" would you put there to handle the problem if it occurs in production? Which exceptions are you going to catch, and what are you going to do to get the app back on track? Whatever happened, it has obviously made even our most basic code untrustworthy. The best we can do is keep an eye on it *during development*, and verify that it behaves sanely there. – jalf Dec 06 '10 at 02:25
  • Of course, any error that *can* be handled should be handled properly. No argument there. But asserts are to catch the errors that can't be handled because you're knee deep in an "impossible" situation that you couldn't have predicted. You can predict that out-of-memory errors may occur, or that a file might be locked, or all sorts of other errors, and those should be handled. But some are conceptually impossible. Calling `sqrt` should return a non-negative number, a normalized vector should have length 1, memory writes should write to memory, and so on. Those things just *have to work*. – jalf Dec 06 '10 at 02:31
  • another point is that of quantity. I can afford to put asserts *everywhere*, even on the most ridiculous things, because I know they're disabled in production, so they won't hurt performance. But if I start writing error handling code around *every* memory write, to verify that the data written to memory is the same as we get if we read back, then the app would just grind to a halt (and I'd have to handle errors in my error handlers, and the compiler would probably run out of memory trying to deal with the billions lines of code I'd have to write to cover everything) – jalf Dec 06 '10 at 02:36
  • Even the most paranoid programmer leaves millions of potential errors unchecked for this reason. Every single line of code contains things that *could* have error handling code written for it, but you never do so. Is that really irresponsible? It's just being realistic. If memory writes don't work, there's nothing you can do, so why bother trying to "handle" it? But if you discover during development that your hardware doesn't handle memory writes properly, then you have time to deal with it, one way or another. – jalf Dec 06 '10 at 02:38
  • @jalf Those are very valid points. True, in performance critical domains -- it is very reasonable to prefer assertions over making an exceptions. I think point to focus on is _in your domain, how important it is to be rigorous about error conditions?_ For example, if I were writing for an architecture wher a segfault will bring the whole machine down (not uncommon in Windows 95 days I guess), it is just responsible to detect the null pointer beforehand, catch the exception and exit nicely. – kizzx2 Dec 06 '10 at 17:23
  • I think the difference here _really_ is about the particular domain -- therefore I'm not saying we should never use assert -- though I do propose that for most everyday programmers, exceptions should be a sensible default. For example, if I am inside a bank database transaction routine, a responsible thing to do is to stop _immediately_ when I detect the program is acting funny, rather than risk it by going further. – kizzx2 Dec 06 '10 at 17:27
  • On the other-hand, I probably won't mind risking it in a video game -- it would be "irreponsible" to stop the player's show even though the game might as well try to push on. Using the memory writing example -- if you're writing to a memory-mapped IO to control a physical device, you'd better stop immediately if the memory-write is acting funny. – kizzx2 Dec 06 '10 at 17:28
  • I do agree a sensible use of assertions is actually encouraged. We don't have the time to evaluate every error condition (again depending on your domain. If I were writing a missle launching software that is _not_ an excuse). Assertions serve just as well as "loud comments" of some sort. – kizzx2 Dec 06 '10 at 17:32
  • I think my concluding point is "exceptions can be handled, but even when unhandled, they serve as safe-guard for undefined behaviors and also a rudimentary error reporting of some sort (nicer than the eventual seg-fault or deleting a random file). I've written more in details in my blog post http://cfc.kizzx2.com/index.php/my-take-on-assertions-vs-exceptions please feel free to comment :) – kizzx2 Dec 06 '10 at 17:32
  • @kizzx2: but if you detect the program acting funny in a bank transaction, that's an obvious example of when to use exception handling. I'd never suggest using asserts there. Once again, asserts are *only* an aid for the developer, in verifying that the program does indeed behave as I expect. If there is *any* chance that it might behave differently at runtime, then I definitely need robust error handling. But for plain "sanity checks", things that aren't really meaningful to "handle" as errors, but which just ease debugging by providing me with the guarantee that "these invariants still hold" – jalf Dec 06 '10 at 20:05
  • every assert that *wasn't* triggered is proof to me that *this part of the app worked as expected*. That's valuable to know when debugging an error. It means we can rule out individual error sources. – jalf Dec 06 '10 at 20:06
  • as programmers we have to take things on faith, no matter how rigorous error handling you write. How do you verify that your exception handler works? You have to trust it. How do you verify that writes to memory happen correctly? You have to trust it. You have to trust that the various instructions do what they're supposed to, and you have to trust that malicious apps won't just rewrite your process' memory. All these things which we *trust* can't be sensibly handled as errors. It would be too slow and too complex, no matter the domain. – jalf Dec 06 '10 at 20:08
  • But we *can* assert that "yes, gravity is still on today", and "yes, the value I wrote to address `X` is still there". All those things that we just *trust*, but that, while debugging, it's nice to be able to confirm. – jalf Dec 06 '10 at 20:09
  • @jalf Thanks for being so descriptive in explaining it, this question and your answer to it have helped me a lot to understand the significance of asserts and when to use them. You've put it in a way no one else could have, thank you, very informative. – Bharat Aug 19 '16 at 15:56
  • In practice the problem is developers never really use the app like a real user. Hence that `fatalError` you placed may never be reached during development. But if the user uses it then somehow they break the app. But we don't have any fatalErrors at that point. Would adding a log next to each `fatalError` be the right choice? Obviously not. I guess you need to have something that combines them both together so you can have development assertions + error logs... – mfaani May 01 '18 at 18:19
  • @Honey it's not uncommon to see something like `assert(condition); if (!condition) {}` in essence - this should never happen, but if it does, we're going to do our best to try and handle it. I'm also in the middle of getting my companies asserts to be a runtime test and log on failure - because frankly - asserts are great, but the people who make the racing car doesn't drive it like the f1 racer. – UKMonkey Aug 04 '20 at 11:52
45

Andrew Koenig used to have a good philosophical discussion over the usage of exceptions and assertions in shipping code. In the end, you're guarding against doing wild things when the program is in an irreparably broken state.

I believe, therefore, that when a program discovers something that is irrefutably wrong with its internal state, it is better off terminating at once, rather than giving its caller the opportunity to pretend that nothing is wrong.

If you like, I think that exceptions should be reserved for situations in which it is possible to do something sensible after catching the exception. When you discover a condition that you thought was impossible, it's hard to say much about what might happen afterward.

metamorphosis
  • 1,972
  • 16
  • 25
cdleary
  • 69,512
  • 53
  • 163
  • 191
  • 5
    Note that the article is still available on [the Internet Archive](https://web.archive.org/web/20090707025230/http://www.ddj.com/blog/cppblog/archives/2007/07/assertions_vers.html). – Qantas 94 Heavy Aug 31 '14 at 01:05
26

From Code Complete 2: "Use error-handling for conditions you expect to occur; use assertions for conditions that should never occur."

A commonly-cited example is checking for zero in the denominator before a division.

You're expected to strip the assertions out of production code. They are in there during development to help you catch mistakes.

Unit tests are not a replacement for assertions.

Nosredna
  • 83,000
  • 15
  • 95
  • 122
  • 1
    "use assertions for conditions that should never occur." I always though that sounded a lot like exception handling. – geowa4 Jul 04 '09 at 03:29
  • 8
    exception handling is for things you know why they occur and that you can deal with inside the program. If an assertion fails something is so wrong you don't know what to do and the program should quit. – Janusz Jul 04 '09 at 03:36
  • 3
    @George IV: The difference is that assertions are for things which you believe that, if your program is correct, are impossible. Exceptions are for things that "shouldn't" happen in the sense that your routine/program cannot work if they do. Hence libraries sometimes throw exceptions for things where an application would assert, since the library doesn't know whether or not the problem is inconceivable from the POV of the program (e.g. out of memory: in some environments you can code to avoid it, in others you can't). – Steve Jessop Jul 04 '09 at 13:08
  • _Unit tests are not a replacement for assertions._ Can you add more to distinguish them? – mfaani May 01 '18 at 18:20
  • I disagree with the statement that you're "expected to strip the assertions out of production code". If a bug is exposed in production, you would rather know about it than not. Also, stripping out assertions may inadvertently introduce bugs into your program, if they happened to have side-effects that you were unaware of. – user2846495 Dec 07 '22 at 15:10
  • I mean obviously it depends on the application domain sorry. If performance is really important then you may want to strip them out. You also probably want to handle them in some way in production, if only to print out a "report this bug" message. – user2846495 Dec 07 '22 at 15:15
9

Because they make debugging easier.

The time consuming part of debugging is tracing a problem from the symptom you first notice back to the error in the code. Well written assertions will make the symptom you notice much closer to the actual code problem.

A very simple example would be a bug where you index past the end of an array and cause memory corruption which eventually causes a crash. It can take a long time to trace back from the crash to the offending index operation. However, if you have an assertion next to that index operation that checks your index, then your program will fail right next to the error, so you'll be able to find the problem quickly.

David Norman
  • 19,396
  • 12
  • 64
  • 54
7

It's a controversial subject. Many people, like myself, do actually prefer to leave them on in production code. If your program is going to go into the weeds anyway, you might as well have the assertion in there so your customer can at least give you the line number and filename (or whatever information or action you configure the assert to do). If you left the assertion out, all the customer could report to you was "it crashed".

This means you probably should not do expensive operations in your assert checks, or at least profile to see if they are going to cause performance problems.

Brian Neal
  • 31,821
  • 7
  • 55
  • 59
6

They enable you to test your assumptions. For example, let's say that you wanted to calculate speed. You would probably want to assert that your calculation is less than the speed of light.

Assertions are for development, to make sure you don't mess up.

geowa4
  • 40,390
  • 17
  • 88
  • 107
3

Just don't use Assertions when you don't want. There is nothing wrong not to use it.

Assertion is only helpful when a test case in debug mode actually hit it. Many times it doesn't hit at all, depends on quality of your test cases. Assertion is used when you try to verify an assumption, so you got what you asked for, you hardly break your assumption during test. That's why you assume it in first place isn't it. Yet there are endless number of "expected impossible" cases that really don't hit your assertion during debug, but somehow still hit in production which have assertion disabled. If you rely on assertion during debug then you most likely end up having some unexpected thing happen in production that even your assertion didn't catch.

Your program should be designed in a strategic way, so that even unexpected matter happen or your test cases didn't cover, a problem is still handled in a defined way, or produce meaningful diagnostic info.

You can use assertion to help troubleshooting, but it is not helpful if you want to prevent problem from happening in first place. The reason is that you can't prevent or handle a niche problem if you assume it won't happen in production (you disable assertion in Production). Good software should catch obvious errors (assertion helps), as well as niche errors (assertion probably won't help).

Many people will tell you a standard version of what is assertion supposed to do. What assertion is good for etc. But please justify by your own experience if it is really helpful or not. Assertion is not scientific proven or golden rule, it is just a practice of many people. You should decide to adopt it or not by yourself.

2

From your post, it sounds like you are not disagreeing with the idea of using assertions, but rather the idea of having assertions in debug and not having them active in production.

The reason for this is that when debugging, you might want the process to fail catastrophically -- i.e. throw an exception and quit, so that the error can be addressed. In production, this could affect your entire system, and the error condition could occur only for a very few cases. So, in production you would probably want to log the error, but keep the process running.

Using assertions lets you change the behavior between debug and release.

I agree with you that the assertions should not just be silenced in production code -- many errors are not exposed in test environments and it is important to know when assertions fail in production.

Larry Watanabe
  • 10,126
  • 9
  • 43
  • 46
  • 3
    assertions slow down code. We used them in videogames and they were there during much of testing. They had to be stripped out after. You don't assert on a GameCube. – Nosredna Jul 04 '09 at 13:36
2

Assertions are invaluable while refactoring I think. If you want to replace alogrihm1() with algorithm2(), you could have them both and assert on the results being equal. You can then gradually phase out the algorithm1()

Asserts are also good for some changes that you might make quickly, but are not too sure of in the context of the state of the system. Setting up asserts for the assumptions you make, would quickly help you to point out the problem, if any.

It is debatable whether asserts should be stripped via using macros or the like in release, but that's what has been done in the projects I have worked on so far.

psquare
  • 79
  • 5
1

In Code complete is a section that says something like. Every time you write an if without any else you are maybe missing something.

It is like this code

int i = 1
i = i++ 

The common programmer will never think about what happens if i is negative in later code. There is the slightly chance of your code producing an overflow and languages like java will jump from max int to min int and you get a very big negative number. This are all the cases you normally say. Uh this will never ever happen. But what is your program doing if it happens? So if you know that there is something that you think will never happen test for it or against it and put an assert false in the else clause that will never happen instead of don't program the else statement. In this way your program should crash completely in the moment you aren't sure any more what it is doing. In production code there should be something different from rather crashing something like informing the user, the maintainer and then exiting.

Another use of assertions is contract driven design. You specify an contract with your interface and depending on your place in the program you assert your input but much more importing you are asserting your output two.

I agree with you that disabled assertions in production code make assertions rather useless. And the default assertions off in case of the java vm is a hazard in my opinion.

Janusz
  • 187,060
  • 113
  • 301
  • 369
1

In many project I've worked in, assertions were done with a custom macro that had different behaviour in Debug and Release.

In Debug, if the condition is false the debugger is started at that point in the code.

In Release, the error is written to a log file, a warning given to the user, and then the system attempts to save unsaved data. Being in an unknown state, this may fail, but it's worth trying.

Pete Kirkham
  • 48,893
  • 5
  • 92
  • 171
1

Asserts should only be used to check conditions during development that are not needed during release.

Here is a really simple example of how assertion can be used in development.

A(char* p)
{
    if(p == NULL)
        throw exception;

    B(p);
    C(p);

}

B(char* p)
{
    assert(p != NULL);
    D(p);
    do stuff;
}

C(char* p)
{
    assert(p != NULL);
    D(p);
    do stuff;
}

D(char* p)
{
    assert(p != NULL);
    do stuff;
}

Instead of calling "if(p == NULL) throw exception;" 5 times, you just call it once so you already know it's not NULL upon entering B(), C(), and D(). Otherwise, an assertion will exit in the development phase because you "changed the code!" not because of a "user's input".

This can make the code run a lot faster in the release version because all you have to do is invoke gcc with "-DNDEBUG" so all of the assertions will not be compiled and all the "unnecessary checks" will be removed in the executable.

0

I've written code where the assertions demonstrably affected performance when enabled. Checking the pre- and post-conditions of maths functions used in tight loops by your graphics code, for example (square root function squares its result and compares it against the input, etc). Sure, it's on the order of a few percentage points, but I've written code that needed those few points.

More importantly, I've written code where the assertions made a tens-of-percentage-points difference to the size of the code. When memory footprint is an issue, asserts in release code are probably an unacceptable extravagance.

Steve Jessop
  • 273,490
  • 39
  • 460
  • 699
0

I use it mostly for tests during development. For instance, here is the smoke test of my utf-8 library Whenever I make a change in the library code I run the tests and if a bug is introduced an assert will trigger. Of course, I could have used a full-blown unit test framework, but for my purposes asserts are just fine.

Nemanja Trifunovic
  • 24,346
  • 3
  • 50
  • 88
0

Can't resist quoting "The indispensable Calvin and Hobbes" p. 180:

Before going down a steep hill like this, one should always give his sled a safety check.
Right.
Seat belts ? None.
Signals ? None.
Brakes ? None.
Steering ? None.
WHEEEEEE

denis
  • 21,378
  • 10
  • 65
  • 88
0

Assertion should be used when you do something like this

a = set()
a.add('hello')
assert 'hello' in a

or

a = 1;
assert a == 1; // if ram corruption happened and flipped the bit, this is the time to assert

As for exceptions, it's something you programmatically deal with:

while True:
  try:
    data = open('sample.file').read()
    break // successfully read
  except IOError:
    // disk read fail from time to time.. so retry
    pass

Most of the time it's safer to restart your application when assert happens, because you don't want to deal with impossible cases. But when the expected case happens (expected errors (most of the time from black-box clients, network calls, etc..) the exceptions should be used.

vtlinh
  • 1,427
  • 3
  • 11
  • 16
0

Assertion should be used for anticipating error in the way a programmer is using an API/function/class/whatever. These bugs need to be fixed quickly at debug time.

For everything else, throw an exception.

balajeerc
  • 3,998
  • 7
  • 35
  • 51
0

For other answers to this question

assert() macro is used to test the conditions or assumptions that should not occur in a program. For example, the array index should always be > 0. Another assumption can be 2+2 == 3+1.

So using assert () we can test such assumptions and as long as they evaluate to true, our program runs normally. When they are false, the program is terminated.

more here https://www.softwaretestinghelp.com/assert-in-cpp/

Peter
  • 1,124
  • 14
  • 17
-3

I NEVER use assertion in my code, I hate them with passion. I understand the need for error checking and handling but to prevent an error that would crash your program by crashing your program yourself .... frankly I do not see the advantage.

Also leave one assertion in your code and murphy's law will ensure that it will, eventually, crash your program. I much prefer checking the data before I do processing with it and throw the appropriate exception so it is handled much like any other exceptional states or operation. This in my experience yielded software that was much more stable in the long run with deterministic behavior from the user's stand point.

You as a software engineer will know what to do when your program asserts out, most users will just get scared they broke something and will end up not using your software. So unless you are developing for engineers (which is quite possible) and even then...

From a usability stand point asserts are horrible, even if they are not "supposed" to happen we all know that eventually it will...


Ok... From all the comment and fire I am getting here I think I need to further explain my point of view because it is clearly not understood.

I did not say I was not checking for exceptions, weird values or just plain wrong states, I just said I did not use assertions because of the horrible way they tent to close the system from a end-user's perspective. Also most modern languages provide another, type-safe way to handle these situations, whey then would I use assert when a perfectly good exception would do the trick, and quite nicely so too.

In most production code I have seen out there I noticed mainly two ways to deal with this, buttering asserts all over the code and then leave a good bunch in production. This has the infuriating tendency to just close the application to the user, I have yet to see an Assert gracefully fail a system.... it just fails it ... boom... gone... end user just saying "WTF is a assertion failed error at address 0x330291ff!!!"

The other way, even worst if you ask me, was to just catch whatever was thrown and hide it under the carpet (ever seen these dreadful try-catch with empty braces !!)

NEITHER WAY will work to get a good stable system. Sure you can use asserts in your beta code and remove them all in your production code... but why the hell would you remove your safety nets because it is production. I would be very surprised that all these checks would cripple your system's performances.

Build yourself a good exception handling scheme and .. by god... LEAVE IT THERE, you will get much more meaningful information our of your system and if done appropriately always in context than having some deep library throwing asserts because something is missing.

This is especially true when creating libraries... to think you, the creator of the library, can decide when to bring down the whole system because something went wrong in the data that was thrown at you is incredibly selfish and narrow minded. Let the user of your library decide what is sufficiently important that it should warrant emergency failure.

so no... I do not use asserts... I use exceptions

And yes... usually the code that fails in production has rarely my name on top.

Newtopian
  • 7,543
  • 4
  • 48
  • 71
  • 1
    they are exactly for this moment. the moment murphys law takes your program and you don't know what it is doing afterwards. If you don't like them you can take them out and add an error handling at the position but if you error handling does something other than display unexpected error ... occured please contact support guy it isn't a place for an assertion and the error handling is correct at this place. – Janusz Jul 04 '09 at 03:49
  • 1
    If you use assertions, then at least you know where your program failed and what internal inconsistency caused it to fail. If you choose to ignore conditions that would cause an assertion to fail, then your program could crash at any later time, or even give wrong results without complaint. Neither of those cases is better for the user, but they are both worse for the programmer trying to debug (and everybody in the tech support chain between the user and the debugger). – user57368 Jul 04 '09 at 03:53
  • Yeah, someday they'll fire in production code. That's a *GOOD* thing assuming your program provides some means of doing an emergency save (assuming it has some sort of document in the first place.) When you hit an impossible situation you should *NOT* attempt to continue. Save, *NOT OVERWRITING*, and exit. – Loren Pechtel Jul 04 '09 at 04:20
  • @Janusz - Personally I think the popup "an error has occurred" or an assert are pretty much equivalent, that is, next to useless if your software stack becomes very large and just degrade really badly the end-user experience. – Newtopian Jul 04 '09 at 07:38
  • @unknown... I can do the same with exception, I see not where an assertion can do more than the exception already can. It the user of my library decides that this exceptional situation is not bad enough and decides to continue nonetheless then the error is his, not mine. Also... he may very well be right, to you, the library creator, it may be an irrecoverable error, but to him, he may have a contingency plan that he can use. Asserts would not give him this flexibility. – Newtopian Jul 04 '09 at 07:43
  • @Loren - wow... so you always have the overview over the whole software stack and can always decide when it should crash down !!?? now there is someone I would not want in my team. If you rely on lower libraries to crash the stack when they do not have proper states then I suggest you expand your horizons and start learning to deal with exceptional situations. It will be hard at first... all this extra code but trust me... your support guy will love you for it, and in 20 years from now may prevent YOU from getting fired. – Newtopian Jul 04 '09 at 07:49
  • Dude you really need to understand stuff more thoroughly before trying to guide others. The only thing you narration tells me is that you dont have a clue what asserts are about. 1. Asserts!=Exceptions 2. They do not crash your program, they halt execution. Big big difference. 3. "most users" will never touch code with asserts in them. They are there in debug builds only. and so on.... – Casper Leon Nielsen Oct 25 '12 at 16:18
  • @CasperLeonNielsen if you read the first answer here he links to a post arguing that Asserts should infact be left in production code. I Agree with the points the author is trying to make in that an application should not try to recover from an error if it risks putitng it in an unstable state. I disagree that Asserts are the proper tool for this. I also strongly dissagree with having code that is different between debug and release. Now you cannot control what the compiler will do but for the parts you can control I really want this to be constant and predictable. – Newtopian Oct 25 '12 at 23:13
  • "[...]should not try to recover from an error if it risks putitng it in an unstable state. I disagree that Asserts are the proper tool for this". I agree, if what you mean is that its not the tool for recovering from critical situations as you describe, but its not the tool for that. This is why I try to point out that you seem to not understand the purpose of asserts. Asserts are there basically to do two things: Document assumptions and give the developers heads up. – Casper Leon Nielsen Oct 26 '12 at 00:01
  • assert(0). No amount of murphy's law will ever make this assert "crash". – Alice Jun 12 '14 at 07:42